Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 728
KotoroShinoto Avatar asked Jul 24 '16 20:07

KotoroShinoto


People also ask

Is Python type hinting enforced?

Python will always remain a dynamically typed language. However, PEP 484 introduced type hints, which make it possible to also do static type checking of Python code. Unlike how types work in most other statically typed languages, type hints by themselves don't cause Python to enforce types.

What is compiled regex?

Compiled Regular Expressions If a Regex object is constructed with the RegexOptions. Compiled option, it compiles the regular expression to explicit MSIL code instead of high-level regular expression internal instructions.

What does regex compile do in Python?

compile() method is used to compile a regular expression pattern provided as a string into a regex pattern object ( re. Pattern ). Later we can use this pattern object to search for a match inside different target strings using regex methods such as a re.

How do you write regex code in Python?

Python has a module named re to work with RegEx. Here's an example: import re pattern = '^a...s$' test_string = 'abyss' result = re. match(pattern, test_string) if result: print("Search successful.") else: print("Search unsuccessful.")


1 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) 
like image 84
Michael0x2a Avatar answered Sep 29 '22 22:09

Michael0x2a