Python: circular imports needed for type checking

后端 未结 4 1297
太阳男子
太阳男子 2021-02-08 02:51

First of all: I do know that there are already many questions and answers to the topic of the circular imports.

The answer is more or less: \"Design your Module/Class s

4条回答
  •  抹茶落季
    2021-02-08 03:16

    Possible duplicate: Python type hinting without cyclic imports

    You should use 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
    

    do:

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

提交回复
热议问题