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

Question:

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?

Asked By: KotoroShinoto

||

Answers:

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)
Answered By: Michael0x2a
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.