我是Mypy的初学者。很快我就意识到,对于这个简单的代码,Mypy失败了(Python 3.8.2,Mypy 0.770):
#!/usr/bin/python3
import re
reserved_words = ("to", "test.te")
reserved_re = map(re.escape, reserved_words)
$ mypy mypy-test1.py
mypy-test1.py:6: error: Argument 1 to "map" has incompatible type "Callable[[AnyStr], AnyStr]"; expected "Callable[[str], AnyStr]"
Found 1 error in 1 file (checked 1 source file)
据我了解,str
应该适合AnyStr
。 AnyStr
的目的是成为bytes
和str
的通用类型。它只会导致Mypy因str
和bytes
的错误组合而失败。
map()
或re.escape()
定义中是否存在错误?我还测试了生成器表达式不会导致Mypy失败:
reserved_re = (re.escape(word) for word in reserved_words)
经过多次尝试,我意识到声明目标变量类型会让Mypy高兴:
reserved_re: typing.Iterator[str] = map(re.escape, reserved_words)