有可能在python中键入提示已编译的正则表达式吗?

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

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

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

python regex type-hinting
1个回答
11
投票

你应该使用专门添加到打字模块的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)
© www.soinside.com 2019 - 2024. All rights reserved.