简体   繁体   English

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

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

I would like to use autocompletion for a pre-compiled and stored list of regular expressions, but it doesn't appear that I can import the _sre.SRE_Pattern class, and I can't programmatically feed the obtained type from type() to a comment of the format # type: classname or use it for a return -> classname style hint我想对预编译和存储的正则表达式列表使用自动完成功能,但似乎我无法导入 _sre.SRE_Pattern 类,并且我无法以编程方式将从 type() 获得的类型提供给格式注释 # type: classname 或将其用于返回 -> classname 样式提示

Is there a way to explicitly import a class from the _sre.c thing?有没有办法从 _sre.c 中显式导入一个类?

You should use typing.Pattern and typing.Match which were specifically added to the typing module to accommodate this use case.您应该使用typing.Patterntyping.Match ,它们是专门添加到typing 模块中以适应此用例的。

Example:示例:

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM