Python type hinting without cyclic imports
<p>I'm trying to split my huge class into two; well, basically into the "main" class and a mixin with additional functions, like so:</p>

<pre><code># main.py
import mymixin.py

class Main(object, MyMixin):
    def func1(self, xxx):
        ...


# mymixin.py
class MyMixin(object):
    def func2(self: Main, xxx):  # &lt;--- note the type hint
        ...
</code></pre>

<p>Now, while this works just fine, the type hint in MyMixin.func2 of course can't work. I can't import main.py, because I'd get a cyclic import and without the hint, my editor (PyCharm) can't tell what <code>self</code> is.</p>

<p>Using Python 3.4, willing to move to 3.5 if a solution is available there.</p>

<p>Is there any way I can split my class into two files and keep all the "connections" so that my IDE still offers me auto completion &amp; all the other goodies that come from it knowing the types?</p>

<p>There isn't a hugely elegant way to handle import cycles in general, I'm afraid. Your choices are to either redesign your code to remove the cyclic dependency, or if it isn't feasible, do something like this:</p>

<pre><code># some_file.py

from typing import TYPE_CHECKING
if TYPE_CHECKING:
    from main import Main

class MyObject(object):
    def func2(self, some_param: 'Main'):
        ...
</code></pre>

<p>The <code>TYPE_CHECKING</code> constant is always <code>False</code> at runtime, so the import won't be evaluated, but mypy (and other type-checking tools) will evaluate the contents of that block.</p>

<p>We also need to make the <code>Main</code> type annotation into a string, effectively forward declaring it since the <code>Main</code> symbol isn't available at runtime.</p>

<p>All that said, using mixins with mypy will likely require a bit more structure then you currently have. Mypy <a href="https://github.com/python/mypy/issues/1996" rel="nofollow">recommends an approach</a> that's basically what <code>deceze</code> is describing -- to create an ABC that both your <code>Main</code> and <code>MyMixin</code> classes inherit. I wouldn't be surprised if you ended up needing to do something similar in order to make Pycharm's checker happy.</p>

python pycharm python-3.4 python-3.5 type-hinting