3.5.1 中关于`namedtuple` 的内容有变化吗? [英] Did something about `namedtuple` change in 3.5.1?

查看:43
本文介绍了3.5.1 中关于`namedtuple` 的内容有变化吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Python 3.5.0 上:

<预><代码>>>>从集合导入namedtuple>>>cluster = namedtuple('Cluster', ['a', 'b'])>>>c = 集群(a=4,b=9)>>>C集群(a=4, b=9)>>>变量(c)OrderedDict([('a', 4), ('b', 9)])

在 Python 3.5.1 上:

<预><代码>>>>从集合导入namedtuple>>>cluster = namedtuple('Cluster', ['a', 'b'])>>>c = 集群(a=4,b=9)>>>C集群(a=4, b=9)>>>变量(c)回溯(最近一次调用最后一次):文件<stdin>",第 1 行,位于 <module>类型错误:vars() 参数必须具有 __dict__ 属性

似乎namedtuple 的某些内容发生了变化(或者可能是关于vars() 的某些内容?).

这是故意的吗?我们不应该再使用这种模式将命名元组转换为字典了吗?

解决方案

Per Python 错误 #24931:

<块引用>

[__dict__] 消失了,因为它在 Python 3 中从根本上被破坏了,所以它必须被删除.提供 __dict__ 会破坏子类化并产生奇怪的行为.

进行更改的修订版

具体来说,没有定义 __slots__ 的子类会表现得很奇怪:

<预><代码>>>>Cluster = namedtuple('Cluster', 'x y')>>>类 Cluster2(Cluster):经过>>>变量(集群(1,2))OrderedDict([('x', 1), ('y', 2)])>>>vars(Cluster2(1,2)){}

使用._asdict().

On Python 3.5.0:

>>> from collections import namedtuple
>>> cluster = namedtuple('Cluster', ['a', 'b'])
>>> c = cluster(a=4, b=9)
>>> c
Cluster(a=4, b=9)
>>> vars(c)
OrderedDict([('a', 4), ('b', 9)])

On Python 3.5.1:

>>> from collections import namedtuple
>>> cluster = namedtuple('Cluster', ['a', 'b'])
>>> c = cluster(a=4, b=9)
>>> c
Cluster(a=4, b=9)
>>> vars(c)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: vars() argument must have __dict__ attribute

Seems like something about namedtuple changed (or maybe it was something about vars()?).

Was this intentional? Are we not supposed to use this pattern for converting named tuples into dictionaries anymore?

解决方案

Per Python bug #24931:

[__dict__] disappeared because it was fundamentally broken in Python 3, so it had to be removed. Providing __dict__ broke subclassing and produced odd behaviors.

Revision that made the change

Specifically, subclasses without __slots__ defined would behave weirdly:

>>> Cluster = namedtuple('Cluster', 'x y')
>>> class Cluster2(Cluster):
    pass
>>> vars(Cluster(1,2))
OrderedDict([('x', 1), ('y', 2)])
>>> vars(Cluster2(1,2))
{}

Use ._asdict().

这篇关于3.5.1 中关于`namedtuple` 的内容有变化吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆