【问题标题】:How do I get a regex pattern type for MyPy如何获取 MyPy 的正则表达式模式类型
【发布时间】:2017-01-24 02:47:52
【问题描述】:

如果我编译一个正则表达式

>>> 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 mypy


【解决方案1】:

Python 3.9 开始,typing.Patterndeprecated

3.9 版后已弃用:来自 re 的类模式和匹配现在支持 []。请参阅 PEP 585 和通用别名类型。

您应该改用 re.Pattern 类型:

import re

def some_func(compiled_regex: re.Pattern):
    ...

【讨论】:

  • 请注意,re.Pattern 本身一开始是通用的,mypy --strict 会抱怨:error: Missing type parameters for generic type "Pattern"typing 文档说:这些类型(和相应的函数)在 AnyStr 中是通用的,可以通过编写 Pattern[str]Pattern[bytes]Match[str]Match[bytes] 来指定。我>
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    是的,re 模块使用的类型实际上不能通过名称访问。您需要使用 typing.re 类型来代替类型注释:

    import typing
    
    def my_func(compiled_regex: typing.re.Pattern):
        ...
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-12
    • 1970-01-01
    • 2011-05-19
    • 2017-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多