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>Yeah, the types the <code>re</code> module uses aren't actually accessible by name. You'll need to use the <a href="https://docs.python.org/3/library/typing.html#typing.re" rel="nofollow"><code>typing.re</code></a> types for type annotations instead:</p>

<pre><code>import typing

def my_func(compiled_regex: typing.re.Pattern):
    ...
</code></pre>

python mypy