我正在尝试用类型注释我的代码,但在涉及集合时我有点困惑。我在 PEP 484 中阅读了一些观点:
Note: Dict , List , Set and FrozenSet are mainly useful for annotating return values. For arguments, prefer the abstract collection types defined below, e.g. Mapping , Sequence or AbstractSet .
和
Set, renamed to AbstractSet . This name change was required because Set in the typing module means set() with generics.
但这并没有帮助。
我的第一个问题是:Set、FrozenSet、MutableSet 和 AbstractSet 之间有什么共同点和不同点?
我的第二个问题是:为什么我要尝试
from collections import FrozenSet
我明白了
ImportError: cannot import name 'FrozenSet'
?
我使用的是 Python 3.4,我已经通过 pip 安装了 mypy-lang。
最佳答案
注意注释和打字。 484 中讨论的想法是全新的,并在 typing
模块中实现。该模块仅在 Python3.5 中可用(对于 Py2 和 Py3,最新的 typing
也可从 pip
获得)。
https://docs.python.org/3/library/typing.html
您引用的注释来自 484 中开始的部分:
To open the usage of static type checking to Python 3.5 as well as older versions, a uniform namespace is required. For this purpose, a new module in the standard library is introduced called typing .
注释列表的内容是注释类型,而不是实际的对象类(内置或来自集合
)。不要混淆两者。
请注意 Dict
、 List
、 Set
和 FrozenSet
都是大写的,其中函数(和类型名称)是 dict
、list
、set
、frozenset
。换句话说,要制作字典,您可以使用 dict()
或 {}
,而不是 Dict
。
注解是 3.0 的新功能(根本不是 2.n 中的)。在常规解释器中,它们所做的只是填充函数的 __annotations__
字典。解释器中没有任何内容使用或需要注释。
http://mypy-lang.org/自称是一个实验性的打字检查器。您需要查看它的文档以了解它与 484 等的兼容性如何。
https://docs.python.org/3/library/collections.abc.html#module-collections.abc有一些抽象定义,我相信 typing
使用。我从来没有用过这些。它们主要供开发新类对象的人使用,而不是“普通”用户。
这个问题的 typing
标签可能不是一个好主意。它的追随者不多,而且过于笼统。它不引用此 Python 模块。
搜索 [python] 484
以获取处理此类注释的其他 SO 问题。
https://github.com/python/typing - typing
开发库。
在此存储库中,python2/typing.py
文件(python2 backport)中有一个FrozenSet
定义,但src/typing 中没有。 py
。我不确定这有什么意义。
关于python - python typing 模块中的 Set、FrozenSet、MutableSet 和 AbstractSet 之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35907309/