How do I get a regex pattern type for MyPy
<p>If I compile a regex</p>

<pre><code>&gt;&gt;&gt; type(re.compile(""))
&lt;class '_sre.SRE_Pattern'&gt;
</code></pre>

<p>And want to pass that regex to a function and use Mypy to type check</p>

<pre><code>def my_func(compiled_regex: _sre.SRE_Pattern):
</code></pre>

<p>I'm running into this problem</p>

<pre><code>&gt;&gt;&gt; import _sre
&gt;&gt;&gt; from _sre import SRE_Pattern
Traceback (most recent call last):
  File "&lt;stdin&gt;", line 1, in &lt;module&gt;
ImportError: cannot import name 'SRE_Pattern'
</code></pre>

<p>It seems that you can import <code>_sre</code> but for some reason <code>SRE_Pattern</code> isn't importable.</p>

<p><code>mypy</code> 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:</p>

<pre><code>import re
from typing import Pattern

def my_func(compiled_regex: Pattern):
    return compiled_regex.flags 

patt = re.compile('') 
print(my_func(patt)) 
</code></pre>

<p>Example run:</p>

<pre><code>$ mypy foo.py 
$ python foo.py 
32
</code></pre>

python mypy