将 {} 绑定到未来版本的 dict()

Bind {} to future version of dict()

我正在升级 Python2 代码以兼容 Python3。作为过程的一部分,我正在使用 future 包将 Python3 行为导入 Python2.

执行此操作时,dict.keys() 方法 returns 一个 Python3 视图对象而不是列表,因此不再需要调用 dict.view_keys()。但是,如果字典是使用 {} 创建的,则 Python2 行为会保留 :

>>> from builtins import *
>>> type({'a':1, 'b':2}.keys())
<type 'list'>
>>> type(dict(a=1, b=2).keys())
<type 'dict_keys'> 

有没有办法将 {} 绑定到新的 dict() class?

恐怕 {} 与解释器的字典(和集合)概念有着不可改变的联系。

另一方面,dict只是全局命名空间中的一个名称,可以很容易地替换;这就是您的图书馆所做的。它不会替换内置字典的实现,它只是添加了自己的实现并使 dict() 指向它。

恐怕没有办法全面替换字典实现,包括 **kwargs 之类的东西,以及使用 {}-语法的标准库的许多部分。

获得 Python 3 行为的预期方法是使用方法 viewkeys(), viewvalues(), and viewitems()

你的例子:

>>> type({'a':1, 'b':2}.viewkeys())
<type 'dict_keys'>

演示如何 dictionary views 操作:

>>> d = {'a':1, 'b':2}
>>> v = d.viewitems()
>>> v
dict_items([('a', 1), ('b', 2)])
>>> d['a'] = 3
>>> v
dict_items([('a', 3), ('b', 2)])