Skip to main content
 首页 » 编程设计

python之Namedtuple '_source' 方法在使用 'exec' 引用后停用

2025年01月19日12cyq1162

_source 是namedtuple 的一种方法,在8.3. collections — Container datatypes — Python 3.6.4rc1 documentation 中指定。 .

使用示例:

In [90]: Book = namedtuple('Book', 'name, author') 
In [91]: Book._source 
Out[91]: "from builtins import property as _property, tuple as _tuple\nfrom operator import itemgetter as _itemgetter\nfrom collections import OrderedDict\n\nclass Book(tuple):\n    'Book(name, author)'\n\n    __slots__ = ()\n\n    _fields = ('name', 'author')\n\n    def __new__(_cls, name, author):\n        'Create new instance of Book(name, author)'\n        return _tuple.__new__(_cls, (name, author))\n\n    @classmethod\n    def _make(cls, iterable, new=tuple.__new__, len=len):\n        'Make a new Book object from a sequence or iterable'\n        result = new(cls, iterable)\n        if len(result) != 2:\n            raise TypeError('Expected 2 arguments, got %d' % len(result))\n        return result\n\n    def _replace(_self, **kwds):\n        'Return a new Book object replacing specified fields with new values'\n        result = _self._make(map(kwds.pop, ('name', 'author'), _self))\n        if kwds:\n            raise ValueError('Got unexpected field names: %r' % list(kwds))\n        return result\n\n    def __repr__(self):\n        'Return a nicely formatted representation string'\n        return self.__class__.__name__ + '(name=%r, author=%r)' % self\n\n    def _asdict(self):\n        'Return a new OrderedDict which maps field names to their values.'\n        return OrderedDict(zip(self._fields, self))\n\n    def __getnewargs__(self):\n        'Return self as a plain tuple.  Used by copy and pickle.'\n        return tuple(self)\n\n    name = _property(_itemgetter(0), doc='Alias for field number 0')\n\n    author = _property(_itemgetter(1), doc='Alias for field number 1')\n\n" 

但是,如果我们使用 exec 引用它,那么随后对 _source 的调用将引发错误。

In [87]: Book = namedtuple('Book', 'name, author') 
In [88]: exec(Book._source) 
In [89]: Book._source 
AttributeError: type object 'Book' has no attribute '_source' 

背后的机制是什么?

请您参考如下方法:

collections.namedtuple 通过填写模板字符串并将其传递给 exec 创建一个类对象。类对象仅在创建后 获得 _source 属性,即,模板字符串未定义它 -- 否则模板将是递归的.这意味着,如果您自己执行 模板,您将获得相同的类,但没有 _source 属性。

然后,exec(Book._source) 在当前命名空间中运行 Book._source 并用新类替换原来的 Book 类从该字符串生成(因为名称匹配),它没有 _source 属性。提供您自己的全局字典并查看差异:

In [1]: from collections import namedtuple 
 
In [2]: Book = namedtuple('Book', 'name, author') 
 
In [3]: ns = {}; exec(Book._source, ns) 
 
In [4]: hasattr(Book, '_source') 
Out[4]: True 
 
In [5]: hasattr(ns['Book'], '_source') 
Out[5]: False 

作为旁注,该属性在 Python 3.7 中被完全删除。