Mypy在使用re.escape()调用map()时抱怨类型不兼容的AnyStr vs str

时间:2020-05-10 09:36:56

标签: python python-3.x mypy

我是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应该适合AnyStrAnyStr的目的是成为bytesstr的通用类型。它只会导致Mypy因strbytes的错误组合而失败。

  • 我的理解错误吗?
  • 我应该在代码中添加一些内容以避免失败吗?
  • Mypy,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)

  • 为什么有必要?
  • 这是预期的行为吗?
  • 首选的“ pythonic”方式是什么?使用生成器表达式还是声明结果类型或其他内容?

0 个答案:

没有答案
相关问题