Circular (or cyclic) imports in Python

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

    Module a.py :

    import b
    print("This is from module a")
    

    Module b.py

    import a
    print("This is from module b")
    

    Running "Module a" will output:

    >>> 
    'This is from module a'
    'This is from module b'
    'This is from module a'
    >>> 
    

    It output this 3 lines while it was supposed to output infinitival because of circular importing. What happens line by line while running"Module a" is listed here:

    1. The first line is import b. so it will visit module b
    2. The first line at module b is import a. so it will visit module a
    3. The first line at module a is import b but note that this line won't be executed again anymore, because every file in python execute an import line just for once, it does not matter where or when it is executed. so it will pass to the next line and print "This is from module a".
    4. After finish visiting whole module a from module b, we are still at module b. so the next line will print "This is from module b"
    5. Module b lines are executed completely. so we will go back to module a where we started module b.
    6. import b line have been executed already and won't be executed again. the next line will print "This is from module a" and program will be finished.

提交回复
热议问题