Python type hinting without cyclic imports

后端 未结 5 896
太阳男子
太阳男子 2020-11-28 04:57

I\'m trying to split my huge class into two; well, basically into the \"main\" class and a mixin with additional functions, like so:

main.py file:

5条回答
  •  长情又很酷
    2020-11-28 05:24

    Turns out my original attempt was quite close to the solution as well. This is what I'm currently using:

    # main.py
    import mymixin.py
    
    class Main(object, MyMixin):
        def func1(self, xxx):
            ...
    
    
    # mymixin.py
    if False:
        from main import Main
    
    class MyMixin(object):
        def func2(self: 'Main', xxx):  # <--- note the type hint
            ...
    

    Note the import within if False statement that never gets imported (but IDE knows about it anyway) and using the Main class as string because it's not known at runtime.

提交回复
热议问题