如何处理名称冲突集合。计数器和键入。计数器?

问题描述 投票:5回答:2

Counter名称在collections(作为类)和typing(作为通用类型名称)中都定义。不幸的是,它们略有不同。建议的处理方式是什么?

相似点和不同点:

  1. from collections import Counter之后,

    1. 您可以调用构造函数Counter("foo")创建一个新的Counter对象;
    2. 您可以确认它是dict的子类:issubclass(Counter, dict)返回True
    3. 您不能使用它来声明Counter的特定变体,例如cnt: Counter[str] = Counter("foo")引发TypeError: 'type' object is not subscriptable(类型提示失败)
  2. from typing import Counter之后,

    1. 您可以调用构造函数Counter("foo")创建一个新的Counter对象(实际上,有些让我惊讶);
    2. 您不能使用它来验证它是dict的子类:issubclass(Counter, dict)引发TypeError: issubclass() arg 1 must be a class;
    3. 您可以声明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

(请注意顺序很重要。)

如果您想拥有全部呢?这些是我看到的选项:

  1. 执行
  2. from collections import Counter
    import typing
    

并使用typing.Counter实现1.3。不好,太罗word了。

  1. 执行
  2. import collections
    from typing import Counter
    

并使用collections.Counter达到2.2(如果需要;我在教学中需要它)。

  1. 执行
  2. from collections import Counter as counter
    from typing import Counter
    

并使用counter达到2.2。

  1. 执行
  2. from collections import Counter
    from typing import Counter as Bag  # or Multiset
    

并在类型提示中使用Bag(或Multiset)。 (但这一定会造成混淆。)

  1. 执行(在注释中建议)
  2. import collections as co  # to access the class
    from typing import Counter  # to access constructor and provide type hints
    

和使用

  1. co.CounterCounter作为构造函数
  2. 使用co.Counter作为类别,例如issubclass(co.Counter, dict)
  3. 在类型提示中使用Counter,例如cnt: Counter[str]
  4. 然后是否也建议这样做

from typing import Deque

并使用Deque作为构造函数,而不是co.deque? (我想/不希望。)

对于其他类型(例如defaultdictdeque),这似乎不是问题:

from collections import defaultdict, deque
from typing import DefaultDict, Deque

给大家。

我在俯视什么吗?

名称Counter在集合(作为类)和键入(作为通用类型名称)中都定义。不幸的是,它们略有不同。建议的处理方式是什么? ...

python collections counter typing
2个回答
0
投票

可能在某些更高级的情况下,这是行不通的,但是您可以创建一个从这两个继承的子类:


0
投票

最少的痛苦可能是解决基于字符串的类型提示。但是,并非每个IDE都会对其进行解释。 PyCharm在此代码段的最后一行检测到类型不匹配,而VSCode认为一切都很好。

© www.soinside.com 2019 - 2024. All rights reserved.