Python `is_trait_type` doesn't work with `Date`

我的梦境 提交于 2019-12-12 01:53:06

问题


In the project I work for, we often need to convert text to the value of a trait. Generally, we use the is_trait_type method to do the appropriate conversion.

However, it doesn't work with Date traits. Here is a MWE:

from traits.has_traits import HasTraits
from traits.trait_types import Int, Date

class A(HasTraits):
    a_date = Date
    an_int = Int

a = A()
class_traits = a.class_traits()
print class_traits["an_int"].is_trait_type(Int)
print class_traits["a_date"].is_trait_type(Date)

The Int behave as expected but the Date fails with:

TypeError: isinstance() arg 2 must be a class, type, or tuple of classes and types

We use Enthought traits module (version 4.1.0) under Ubuntu 14.04.


回答1:


As mentioned in the comments, Date (and Time) trait types are not classes but instances. The is_trait_type(x) method checks whether self.trait_type is an instance of the provided class (i.e. the value of x), and hence it fails if x is not a class. In my opinion, this a bug in the API.

If you need a workaround, you can define a method like this:

def my_is_trait_type(trait, trait_type):
    if isinstance(trait_type, BaseInstance):
        return trait.is_trait_type(trait_type.__class__)
    else:
        return trait.is_trait_type(trait_type)

However, I would reconsider using is_trait_type() for the task of finding the appropriate conversion. Maybe a map would do, for instance.



来源:https://stackoverflow.com/questions/29671969/python-is-trait-type-doesnt-work-with-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!