Python:对其他模块变量的更改未反映

时间:2018-08-01 17:23:13

标签: python import module scope package

请解释输出内容?

                           # maindir/config/config.py                    
foo = 0
                           # maindir/worker/worker.py                    
import maindir.config.config

def print_foo():
    print maindir.config.config.foo
                           # maindir/main.py                    
import config.config
import worker.worker

if __name__ == '__main__':
    print config.config.foo
    config.config.foo = 5
    print config.config.foo
    worker.worker.print_foo()

输出:

$ env PYTHONPATH=. python maindir/main.py
0
5
0                          # was expecting 5 ...

另一方面,如果我们在import config.config中切换到worker.py,那么也就不足为奇了:

                           # maindir/worker/worker.py                    
import config.config

def print_foo():
    print config.config.foo

输出:

$ env PYTHONPATH=./maindir python maindir/main.py
0
5
5

0 个答案:

没有答案