python - python typing 模块中的 Set、FrozenSet、MutableSet 和 AbstractSet 之间有什么区别?

标签 python python-3.x type-hinting frozenset

我正在尝试用类型注释我的代码,但在涉及集合时我有点困惑。我在 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 .

注释列表的内容是注释类型,而不是实际的对象类(内置或来自集合)。不要混淆两者。

请注意 DictListSetFrozenSet 都是大写的,其中函数(和类型名称)是 dictlistsetfrozenset。换句话说,要制作字典,您可以使用 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/

相关文章:

python - 用日志数量而不是 %asctime 标记 python 记录器文件

python - Typehint 使用 importlib 动态导入模块

python - Pytorch (1.0) 中类似外观操作的不同 `grad_fn`

python - 大多数Pythonic方式打印*最多*一些小数位

python-3.x - 如何使用 tfrecord 中的 python API 从 Google Earth 引擎下载哨兵图像

python - 比较 python 中的事物

python - 在 Python 中,在包含字符串和 float 的列表中找到最小值的最简单方法是什么?

type-hinting - 如何正确键入提示类装饰器?

python - 为仅返回一组特定值的函数键入提示

python - os.walk 正则表达式