Search code examples
pythonmypy

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 _sre but for some reason SRE_Pattern isn't importable.


Solution

  • For Python>3.9, refer to this answer by Rotareti, and this Q&A for further background about the support for generic alias type.

    Historic answer follows.


    mypy is very strict in terms of what it can accept, so you can't just generate the types or use import locations that it doesn't know how to support (otherwise it will just complain about library stubs for the syntax to a standard library import it doesn't understand). Full solution:

    import re
    from typing import Pattern
    
    def my_func(compiled_regex: Pattern):
        return compiled_regex.flags 
    
    patt = re.compile('') 
    print(my_func(patt)) 
    

    Example run:

    $ mypy foo.py 
    $ python foo.py 
    32