是否可以在 python 中对已编译的正则表达式进行类型提示?

Is it possible to type-hint a compiled regex in python?

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

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

您应该使用 typing.Pattern and 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)