gpt4 book ai didi

python - 我在哪里可以找到 dict_keys 类?

转载 作者:太空宇宙 更新时间:2023-11-04 08:03:31 24 4
gpt4 key购买 nike

如何直接在 dict_keys 类上获取引用?目前我能找到的唯一方法是创建一个临时 dict 对象并对其进行类型检查。

>>> the_class = type({}.keys())
>>> the_class
<class 'dict_keys'>
>>> the_class.__module__
'builtins'
>>> import builtins
>>> builtins.dict_keys
AttributeError: module 'builtins' has no attribute 'dict_keys'

最佳答案

这就是你“应该”这样做的方式,尽管我一直困扰的唯一原因是修复 Py 2.7 中的错误,其中 dict_keys不是 collections.KeysView 的虚拟子类,我使用该技术来执行 Py3 默认执行的操作。

collections.abc (在 Python 中实现,而不是 C)registers the type作为 collections.abc.KeysView 的虚拟子类, it does :

dict_keys = type({}.keys())
... many lines later ...
KeysView.register(dict_keys)

因为该类不会以其他方式在 Python 层公开。我想如果 Python 本身没有更好的方法来完成任务,它可能是正确的方法。当然,你总是可以借用 Python 的劳动成果:

# Can't use collections.abc itself, because it only imports stuff in
# _collections_abc.__all__, and dict_keys isn't in there
from _collections_abc import dict_keys

但考虑到 _collections_abc是未记录的(除了 the collections.abc documentation 中的源代码链接,我怀疑这是否构成保留它的约束力契约(Contract)),我会坚持使用 dict_keys = type({}.keys()) (不依赖于任何未记录的行为),或者当您执行 isinstance 时基于类型检查,使用 collections.abc.KeysView 相反。

关于python - 我在哪里可以找到 dict_keys 类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35784289/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com