我的问题
我正在编写一个带有计数器的 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以使其方法(如total
)被 mypy 识别的正确方法是什么?