Circular (or cyclic) imports in Python

前端 未结 12 2385
醉梦人生
醉梦人生 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:53

    I solved the problem the following way, and it works well without any error. Consider two files a.py and b.py.

    I added this to a.py and it worked.

    if __name__ == "__main__":
            main ()
    

    a.py:

    import b
    y = 2
    def main():
        print ("a out")
        print (b.x)
    
    if __name__ == "__main__":
        main ()
    

    b.py:

    import a
    print ("b out")
    x = 3 + a.y
    

    The output I get is

    >>> b out 
    >>> a out 
    >>> 5
    

提交回复
热议问题