Python Module Initialization Order?

后端 未结 2 1761
半阙折子戏
半阙折子戏 2020-12-06 05:34

I am a Python newbie coming from a C++ background. While I know it\'s not Pythonic to try to find a matching concept using my old C++ knowledge, I think this question is sti

2条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-06 06:06

    Python import executes new Python modules from beginning to end. Subsequent imports only result in a copy of the existing reference in sys.modules, even if still in the middle of importing the module due to a circular import. Module attributes ("global variables" are actually at the module scope) that have been initialized before the circular import will exist.

    main.py:

    import a
    

    a.py:

    var1 = 'foo'
    import b
    var2 = 'bar'
    

    b.py:

    import a
    print a.var1 # works
    print a.var2 # fails
    

提交回复
热议问题