3

By Google Python style guide, one disadvantage of using global variables is this:

"Has the potential to change module behavior during the import, because assignments to module-level variables are done when the module is imported".

My understanding to the sentence is, "the module level variables of the imported module A effect the behavior of module B which imports module A", is this semantically correct?

If it is, any module level variable var in A can only be accessed in B by A.var. I don't get why importing A would change the behavior of B.

If I misunderstand the sentence, what is the correct interpretation?

Thanks!

4

2 回答 2

0

我相信有一个导入缓存可以避免在执行单个程序期间多次重新导入同一个模块。

但是,例如,模块级全局可以设置为由 time.time() 或类似方法播种的随机数。如果将随机数用作除数,则有时在导入模块时会被除以零,有时则不会。

于 2013-04-28T03:11:26.913 回答
0

在考虑了我的问题一段时间后,我有了以下想法。

考虑以下三个文件:

文件 1:foo.py

x = 1

文件 2:bar.py

import foo
foo.x = 2
def func():
  pass

文件 3:main.py

import foo
foo.x = 3

# Now I need some function in bar...    
import bar
bar.func()

print foo.x

只浏览main.py很难想象为什么foo.x会是 2。这是因为当main.py导入bar时, foo.x 的值在bar.py中发生了变化

这可能不是最好的答案。欢迎您指正或添加更多解释。

于 2013-04-29T14:24:25.430 回答