如何在Python中实现类/对象元数据?

时间:2011-10-05 14:24:15

标签: python class coding-style metadata

我正在开发一个基于nodes之间的流数据的结构化数据分析框架。目前,节点被实现为框架提供的根节点类的子类。对于每个节点类/工厂,我需要元数据,例如节点属性列表,它们的描述,节点输出。元数据可能是:对于前端应用程序中的最终用户或编程用户 - 一些其他流管理工具。将来会有更多的。

(请注意,我在编写代码时才开始学习python)

目前,元数据是在类变量

中提供的
class AggregateNode(base.Node):
    """Aggregate"""

    __node_info__ = {
        "label" : "Aggregate Node",
        "description" : "Aggregate values grouping by key fields.",
        "output" : "Key fields followed by aggregations for each aggregated field. Last field is "
                   "record count.",
        "attributes" : [
            {
                 "name": "keys",
                 "description": "List of fields according to which records are grouped"
            },
            {
                "name": "record_count_field",
                 "description": "Name of a field where record count will be stored. "
                                "Default is `record_count`"
            }
        ]
    }

可以找到更多示例here

我觉得可以用更清洁的方式完成。有一个限制:由于节点是自定义子类,因此对潜在的未来属性名称的干扰最小。

我想要做的是拆分当前的 node_info 。它本来是私有的框架,但现在我意识到它有更广泛的用途。我在考虑使用node_属性:将具有公共属性名称空间,而不会从潜在的自定义节点属性中获取太多名称。

我的问题是:在python程序中提供此类元数据的最常用方法是什么?带字典的单变量?多个变量,每个元数据属性一个? (这会与限制相冲突)自定义类/结构?使用某种前缀,如node_ *并使用多个变量?

3 个答案:

答案 0 :(得分:1)

我不确定是否有一些“标准”方法在python对象中存储自定义元数据,但作为一个例子,dbus的python实现将"_dbus" prefix的属性添加到已发布的方法和信号中。

答案 1 :(得分:1)

您所描述的许多功能与epydoc重叠:

>>> class AggregateNode(base.Node):
...     r"""
...     Aggregate values grouping by key fields.
... 
...     @ivar keys: List of fields according to which records are grouped
... 
...     @ivar record_count_field: Name of a field where record count will be
...                               stored.
...     """
...     record_count_field = "record_count"
...     
...     def get_output(self):
...         r"""
...         @return: Key fields followed by aggregations for each aggregated field.
...                  Last field is record count.
...         """
... 
>>> import epydoc.docbuilder
>>> api = epydoc.docbuilder.build_doc(AggregateNode)
>>> api.variables['keys'].descr.to_plaintext(None)
u'List of fields according to which records are grouped\n\n'
>>> api.variables['record_count_field'].value.pyval
'record_count'

答案 2 :(得分:0)

能够修改类定义本身(因此是元数据)的Python类的唯一元素是__new__()函数,在实际创建对象之前调用new,之后启动。在使用__init__()初始化之前,您可以使用它来读取/修改类/节点内部结构