检查同步特征:Traits / TraitsUI

时间:2015-01-26 07:43:10

标签: python enthought traits traitsui

我在一个大型程序中扫描所有特征,我们的许多特征是同步的。例如,考虑结构的HasTrait对象:

a = Material1.ShellMaterial
b = Material2.CoreMaterial
c = Material3.MaterialX

在我们的应用程序中,事实证明a和c是同步特征。换句话说,Material3.MaterialXMaterial1.ShellMaterial相同,并且已使用sync_trait() (HasTraits API)进行设置。

是否可以检查a,b,c并动态确定a和c是否已同步?

目标是绘制所有这些,但隐藏用户的多余图。尽管这些对象代表相同的数据,但a==c返回False之间的典型比较。

1 个答案:

答案 0 :(得分:1)

据我所知,没有官方API允许检查特征的同步状态。

当然,您可以再次调用sync_trait()方法以确保特征是同步的(如果使用remove=True,则不同步)。因此,您将知道特征的同步状态。

如果您不想更改同步状态,则必须依赖非官方API函数,这些函数未记录且可能会更改 - 因此使用它们需要您自担风险。

from traits.api import HasTraits, Float
class AA(HasTraits):
    a =Float()
class BB(HasTraits):
    b = Float()
aa = AA()
bb = BB()
aa.sync_trait("a", bb, "b")

# aa.a and bb.b are synchronized
# Now we use non-official API functions
info = aa._get_sync_trait_info()

synced = info.has_key("a") # True if aa.a is synchronized to some other trait
if synced:
    sync_info = info["a"] # fails if a is not a synchronized trait
    # sync_info is a dictionary which maps (id(bb),"b") to a tuple (wr, "b")
    # If you do not know the id() of the HasTraits-object and the name of
    # the trait, you have to loop through all elements of sync_info and
    # search for the entry you want...
    wr, name = sync_info[(id(bb), "b")]
    # wr is a weakref to the class of bb, and name is the name 
    # of the trait which aa.a is synced to
    cls = wr() # <__main__.BB at 0x6923a98>

同样,使用风险自负,但它对我有用。