Counter
名称在collections
(作为类)和typing
(作为通用类型名称)中都定义。不幸的是,它们略有不同。建议的处理方式是什么?
相似点和不同点:
from collections import Counter
之后,
Counter("foo")
创建一个新的Counter
对象;dict
的子类:issubclass(Counter, dict)
返回True
;Counter
的特定变体,例如cnt: Counter[str] = Counter("foo")
引发TypeError: 'type' object is not subscriptable
(类型提示失败)from typing import Counter
之后,
Counter("foo")
创建一个新的Counter
对象(实际上,有些让我惊讶);dict
的子类:issubclass(Counter, dict)
引发TypeError: issubclass() arg 1 must be a class
;Counter
的特定变体,例如cnt: Counter[str] = Counter("foo")
。在许多情况下,1.1和2.1足够好,因此导入的选择无关紧要。但是似乎您不能同时使用1.3和2.2进行单个导入。在后两者中,类型提示比子类检查更重要。如果要编写类型提示,则from typing import Counter
就足够了。但是,如果您编写的话,我会发现它更清晰(并且更符合某些其他类型的要求)
from collections import Counter # to indicate that you want the implementation from typing import Counter # to indicate that you want to write type hints
(请注意顺序很重要。)
如果您想拥有全部呢?这些是我看到的选项:
from collections import Counter
import typing
并使用typing.Counter
实现1.3。不好,太罗word了。
import collections
from typing import Counter
并使用collections.Counter
达到2.2(如果需要;我在教学中需要它)。
from collections import Counter as counter
from typing import Counter
并使用counter
达到2.2。
from collections import Counter
from typing import Counter as Bag # or Multiset
并在类型提示中使用Bag
(或Multiset
)。 (但这一定会造成混淆。)
import collections as co # to access the class
from typing import Counter # to access constructor and provide type hints
和使用
co.Counter
或Counter
作为构造函数co.Counter
作为类别,例如issubclass(co.Counter, dict)
Counter
,例如cnt: Counter[str]
然后是否也建议这样做
from typing import Deque
并使用
Deque
作为构造函数,而不是co.deque
? (我想/不希望。)
对于其他类型(例如defaultdict
和deque
),这似乎不是问题:
from collections import defaultdict, deque from typing import DefaultDict, Deque
给大家。
我在俯视什么吗?
名称Counter在集合(作为类)和键入(作为通用类型名称)中都定义。不幸的是,它们略有不同。建议的处理方式是什么? ...
可能在某些更高级的情况下,这是行不通的,但是您可以创建一个从这两个继承的子类:
最少的痛苦可能是解决基于字符串的类型提示。但是,并非每个IDE都会对其进行解释。 PyCharm在此代码段的最后一行检测到类型不匹配,而VSCode认为一切都很好。