how do imports work for a module used as a singleton?

I'm confused about what happens if you tread a module as a singleton.

Say I have a module conf.py, that contains some configuration parameters which need to be accessed by multiple other files. In conf.py, I might have this piece of code (and nothing else):

myOption = 'foo' + 'bar'

If I now import it first in a.py, and then in b.py, my understanding is that the first time it is imported (in a.py), the string concatenation will be executed. But the second time it is imported (in b.py), conf.myOption already has its value, so no string concatenation will be executed. Is this correct?

If after doing these two imports, I then execute the following in b.py

conf.myOption = 'aDifferentFoobar'

then obviously b.py would now see this new value. Would a.py see the same value, or would it still see 'foobar'?

I believe (but correct me if I'm wrong) that imports are always referred to by reference, not by value? And I'm guessing that's what the above questions boil down to.


Try it and see:

mod.py :

def foo():
    print("in foo()")
    return "foo"

bar = foo()
opt = "initial"

b.py :

import mod

mod.opt = "changed"

a.py :

import mod
import b

print(mod.bar)
print(mod.opt)

Execute a.py :

$ python3.4 a.py

Output:

in foo()
foo
changed

We learn:

  • foo() is only executed once
  • mod.opt is changed by b.py
  • a.py sees the changed value of mod.opt
  • bonus: the order of import s in a.py does not matter
  • 链接地址: http://www.djcxy.com/p/54804.html

    上一篇: 为什么要编译Python代码?

    下一篇: 导入如何用作用作单例模块的​​模块?