Python: circular imports needed for type checking

后端 未结 4 1289
太阳男子
太阳男子 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:21

    The best solution is to not check types.

    The other solution is to not create an instance of, and not reference at all, Foo or Bar until both classes are loaded. If the first module is loaded first, don't create a Bar or refer to Bar until after the class Foo statement is executed. Similarly, if the second module is loaded first, don't create a Foo or reference Foo until after the class Bar statement is executed.

    This is basically the source of the ImportError, which could be avoided if you did "import foo" and "import bar" instead, and used foo.Foo where you now use Foo, and bar.Bar where you now use Bar. In doing this, you no longer refer to either of them until a Foo or Bar is created, which hopefully won't happen until after both are created (or else you'll get an AttributeError).

提交回复
热议问题