Python type hinting without cyclic imports

后端 未结 5 903
太阳男子
太阳男子 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

    For people struggling with cyclic imports when importing class only for Type checking: you will likely want to use a Forward Reference (PEP 484 - Type Hints):

    When a type hint contains names that have not been defined yet, that definition may be expressed as a string literal, to be resolved later.

    So instead of:

    class Tree:
        def __init__(self, left: Tree, right: Tree):
            self.left = left
            self.right = right
    

    you do:

    class Tree:
        def __init__(self, left: 'Tree', right: 'Tree'):
            self.left = left
            self.right = right
    

提交回复
热议问题