如果我编译正则表达式
>>> type(re.compile(""))
<class '_sre.SRE_Pattern'>
并且想要将该正则表达式传递给函数并使用 Mypy 进行类型检查
def my_func(compiled_regex: _sre.SRE_Pattern):
我遇到了这个问题
>>> import _sre
>>> from _sre import SRE_Pattern
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'SRE_Pattern'
似乎您可以导入
_sre
,但由于某种原因 SRE_Pattern
无法导入。
对于 Python>3.9,请参阅 Rotareti 的这个答案。
历史性的答案如下。
mypy
在它可以接受的方面非常严格,所以你不能只生成类型或使用它不知道如何支持的导入位置(否则它只会抱怨语法的库存根它不理解的标准库导入)。完整解决方案:
import re
from typing import Pattern
def my_func(compiled_regex: Pattern):
return compiled_regex.flags
patt = re.compile('')
print(my_func(patt))
运行示例:
$ mypy foo.py
$ python foo.py
32
从 Python 3.9
typing.Pattern
开始已弃用。
自 3.9 版起已弃用:re 中的 Pattern 和 Match 类现在支持 []。请参阅 PEP 585 和通用别名类型。
您应该使用类型
re.Pattern
来代替:
import re
def some_func(compiled_regex: re.Pattern):
...
是的,
re
模块使用的类型实际上无法通过名称访问。您需要使用 typing.re
类型来进行类型注释:
import typing
def my_func(compiled_regex: typing.re.Pattern):
...