是否可以在Python中键入提示已编译的正则表达式?

问题描述 投票:0回答:1

我想对预编译和存储的正则表达式列表使用自动完成功能,但似乎我无法导入 _sre.SRE_Pattern 类,并且我无法以编程方式将获得的类型从 type() 提供给格式为 # type: classname 的注释或将其用于 return -> classname 样式提示

有没有办法从 _sre.c 中显式导入类?

python regex python-typing
1个回答
81
投票

您应该使用

typing.Pattern
typing.Match
,它们是专门添加到打字模块中以适应此用例的。

示例:

from typing import Pattern, Match
import re

my_pattern = re.compile("[abc]*")  # type: Pattern[str]
my_match = re.match(my_pattern, "abbcab")  # type: Match[str]
print(my_match)
© www.soinside.com 2019 - 2024. All rights reserved.