简体   繁体   中英

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

Is there a way to explicitly import a class from the _sre.c thing?

You should use typing.Pattern and typing.Match which were specifically added to the typing module to accommodate this use case.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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