如果我编译了一个正则表达式
>>> type(re.compile(""))
<class '_sre.SRE_Pattern'>并希望将该正则表达式传递给函数,并使用Mypy键入check
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并不重要。
发布于 2016-09-16 00:00:55
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发布于 2021-02-26 11:33:36
从Python3.9开始, typing.Pattern是已弃用。
从版本3.9: Classes模式和Match开始不再受欢迎,因为re现在支持[]。参见PEP 585和通用别名类型。
您应该使用re.Pattern类型来代替:
import re
def some_func(compiled_regex: re.Pattern):
...发布于 2016-09-15 23:48:31
是的,re模块使用的类型实际上不能按名称访问。您需要将typing.re类型用于类型注释:
import typing
def my_func(compiled_regex: typing.re.Pattern):
...https://stackoverflow.com/questions/39521895
复制相似问题