18

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.

max
  • 49,282
  • 56
  • 208
  • 355
AlexLordThorsen
  • 8,057
  • 5
  • 48
  • 103

3 Answers3

23

For Python>3.9, refer to this answer by Rotareti.

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
metatoaster
  • 17,419
  • 5
  • 55
  • 66
10

Starting from Python 3.9 typing.Pattern is deprecated.

Deprecated since version 3.9: Classes Pattern and Match from re now support []. See PEP 585 and Generic Alias Type.

You should use the type re.Pattern instead:

import re

def some_func(compiled_regex: re.Pattern):
    ...
Rotareti
  • 49,483
  • 23
  • 112
  • 108
  • 4
    Note that `re.Pattern` itself is generic at first and `mypy --strict` will complain: `error: Missing type parameters for generic type "Pattern"`. The `typing` docs say: *These types (and the corresponding functions) are generic in `AnyStr` and can be made specific by writing `Pattern[str]`, `Pattern[bytes]`, `Match[str]`, or `Match[bytes]`.* – Alex Povel Dec 31 '21 at 15:46
2

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

import typing

def my_func(compiled_regex: typing.re.Pattern):
    ...
user2357112
  • 260,549
  • 28
  • 431
  • 505