【问题标题】:Is it possible to iterate through class trait in order of declaration using Enthought traits?是否可以使用 Enthought 特征按声明顺序遍历类特征?
【发布时间】:2017-03-15 09:30:36
【问题描述】:

我们使用 Enthought Traits 来声明一些用于创建数据库模式的 python 类和用于添加记录的 UI。所以我们有代码来遍历类特征并执行一些操作。一个常见问题是声明的顺序通常对理解架构和 UI 非常重要或非常有帮助,但此顺序在 class_traits 中丢失了(因为它是一个 python 字典)。

有没有办法自动保持class_traits中的申报顺序?也许通过覆盖HasTraits 中的某些方法?

我们现在使用 python 2(我们正在迁移到 python 3,但这需要时间)。

编辑:在发帖之前,我发现this question 提出了一个类似于 Robert Kern 建议但没有 sn-p 的技巧。我期待 Traits 会在那里提供一些帮助。无论如何,罗伯特的回答很有用。

【问题讨论】:

    标签: python enthought


    【解决方案1】:

    在 Python 2 中并不容易。Python 2 根本不保留这些信息。

    如果您使用可用的.py 源运行,则可以从该文件重新解析类定义并以这种方式重建顺序。如果你不是,那么我想你可以尝试解析字节码,但你自己在那里。

    import ast
    import inspect
    
    
    def ordered_class_traits(cls):
        source = inspect.getsource(cls)
        mod_ast = ast.parse(source)
        class_trait_names = cls.class_trait_names()
        class_ast = mod_ast.body[0]
        for node in class_ast.body:
            # This probably doesn't capture every possible trait declaration
            # out there, but it does the job for most of them.
            if isinstance(node, ast.Assign):
                target = node.targets[0]
                if isinstance(target, ast.Name):
                    if target.id in class_trait_names:
                        yield target.id
    

    【讨论】:

    • 感谢代码 sn-p。我会建议是否可以包含它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-03
    • 2021-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-12
    相关资源
    最近更新 更多