我正在编写一个带有 Counter 的 Python 函数,用于计算字符串并打印计数的字符串总数。我尝试以各种方式注释该函数。但都没有通过 mypy 测试:
from collections import Counter
import typing
def f1(c : Counter[str]) -> None:
print(c.total())
def f2(c : Counter) -> None:
print(c.total())
def f3(c : Counter[str, int]) -> None:
print(c.total())
c : Counter = Counter()
c.update(['a', 'b', 'c', 'a', 'b', 'c'])
f1(c)
f2(c)
f3(c)
use_counter.py:5: error: "Counter[str]" has no attribute "total"
use_counter.py:8: error: "Counter[Any]" has no attribute "total"
use_counter.py:10: error: "Counter" expects 1 type argument, but 2 given
use_counter.py:11: error: "Counter[Any]" has no attribute "total"
注释
Counter
的各种方式(在 f1
、f2
和 f3
)和谷歌搜索答案。
注释 collections.Counter 以便 mypy 识别其方法(如
total
)的正确方法是什么?
Counter.total
在 0.940 版本中被添加到 mypy。您的代码 f1 和 f2 部分工作正常
from collections import Counter
def f1(c: Counter[str]) -> None:
print(c.total())
def f2(c: Counter) -> None:
print(c.total())
c: Counter = Counter()
c.update(["a", "b", "c", "a", "b", "c"])
f1(c)
f2(c)