Python:我可以在包 __init__ 模块中设置全局变量吗?

标签 python initialization global-variables pytables

所以我正在阅读 Alex Martelli 对 other question 的回答...

"One example in which I may want initialization is when at package-load time I want to read in a bunch of data once and for all (from files, a DB, or the web, say) -- in which case it's much nicer to put that reading in a private function in the package's init.py rather than have a separate "initialization module" and redundantly import that module from every single real module in the package..."

不幸的是,当我尝试这个时:

foo/__init__.py

import tables as tb
global foo
foo = tb.openFile('foo.h5', etc._)
import bar

foo/bar/__init__.py

import tables as tb
global bar
bar = foo.createGroup('/', bar)
import MyFunction`

foo/bar/MyFunction.py

def MyFunction(*of foo and bar*):
   '...'

>>> import foo
>>> OUTPUT= foo.bar.MyFunction.MyFunction(INPUT)
>>> bar = foo.createGroup('/', bar)
NameError: name 'foo' is not defined

如何定义全局变量而不将它们放入函数中(如 here 所示)?

最佳答案

全局变量不是全局的,因为 Python 代码的每一部分都看到相同的全局变量集。全局性实际上只是“模块范围”;模块中定义的所有变量和函数都已经是全局的,并且尽可能全局。

如果您想在另一个模块的全局变量中查看一个模块中定义的变量,唯一的方法是将第一个模块的名称导入到第二个模块中...IE:

# myModule.py
foo = "bar"
# yourModule.py
from myModule import foo

关于Python:我可以在包 __init__ 模块中设置全局变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13280822/

相关文章:

python opencv导入库错误

c++:如何初始化已使用 malloc 分配的 std::mutex?

c - 用一个值初始化整个二维数组

perl - 如何减少 Perl CGI 脚本的启动时间?

javascript - 太多的 if-else 语句。它们可以全局化吗?

c - 定义全局变量,在 main 中得到不同的结果

python - 如何以适当的方式关闭线程和启动线程?

再次使用 Python 正则表达式 - 匹配 URL

javascript - 从事件监听器更新全局变量

python - 使用 Popen 在 Python 中设置环境变量