AlexLordThorsen AlexLordThorsen - 1 year ago 108
Python Question

How do I get a regex pattern type for MyPy

If I compile a regex

>>> type(re.compile(""))
<class '_sre.SRE_Pattern'>

And want to pass that regex to a function and use Mypy to type check

def my_func(compiled_regex: _sre.SRE_Pattern):

I'm running into this problem

>>> import _sre
>>> from _sre import SRE_Pattern
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: cannot import name 'SRE_Pattern'

It seems that you can import
but for some reason
isn't importable.

Answer Source

Yeah, the types the re module uses aren't actually accessible by name. You'll need to use the types for type annotations instead:

import typing

def my_func(compiled_regex:
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download