Circular (or cyclic) imports in Python

前端 未结 12 2308
醉梦人生
醉梦人生 2020-11-21 05:23

What will happen if two modules import each other?

To generalize the problem, what about the cyclic imports in Python?

12条回答
  •  南笙
    南笙 (楼主)
    2020-11-21 05:33

    I completely agree with pythoneer's answer here. But I have stumbled on some code that was flawed with circular imports and caused issues when trying to add unit tests. So to quickly patch it without changing everything you can resolve the issue by doing a dynamic import.

    # Hack to import something without circular import issue
    def load_module(name):
        """Load module using imp.find_module"""
        names = name.split(".")
        path = None
        for name in names:
            f, path, info = imp.find_module(name, path)
            path = [path]
        return imp.load_module(name, f, path[0], info)
    constants = load_module("app.constants")
    

    Again, this isn't a permanent fix but may help someone that wants to fix an import error without changing too much of the code.

    Cheers!

提交回复
热议问题