[英]Accessing variable in module / Module scope in Python
I would like to use a variable that I define in my application inside of a module. 我想在模块内的应用程序中使用定义的变量。
The folder structure: 文件夹结构:
myapp.py
myapp.py
modules/checkargs.py
modules / checkargs.py
modules/ init .py (an empty file)
modules / init .py(一个空文件)
Main app (myapp.py): 主应用程序(myapp.py):
_PARAMETERS = {
'stuff': 'here'
}
from modules.checkargs import checkargs
if __name__ == "__main__":
checkargs(sys.argv[1:])
checkargs.py: checkargs.py:
def checkargs(argv):
global _PARAMETERS;
#more Python insanity here
The error: 错误:
NameError: global name '_PARAMETERS' is not defined
NameError:全局名称“ _PARAMETERS”未定义
In general, you should avoid this style of programming. 通常,您应该避免这种编程风格。 Modules shouldn't rely on global variables defined in other modules.
模块不应依赖于其他模块中定义的全局变量。 A better solution would be to pass
_PARAMETERS
in to checkargs
, or move _PARAMETERS
to a file that can be shared by multiple modules. 更好的解决方案是将
_PARAMETERS
传递到checkargs
,或将_PARAMETERS
移至可以由多个模块共享的文件。
Generally speaking, relying on global variables is a bad idea. 一般来说,依靠全局变量是一个坏主意。 Perhaps the best solution is to pass
PARAMETERS
directly into your checkargs
function. 也许最好的解决方案是将
PARAMETERS
直接传递到您的checkargs
函数中。
# checkargs.py
def checkargs(argv, parameters):
...
# myapp.py
if __name__ == "__main__":
checkargs(sys.argv[1:], _PARAMETERS)
If you have data that you want to share between modules, you can place that data in a third module that every other module imports: 如果您有要在模块之间共享的数据,则可以将该数据放在每个其他模块导入的第三个模块中:
# modules/shared.py
PARAMETERS = {...}
# myapp.py
from modules.shared import PARAMETERS
# checkargs.py
from modules.shared import PARAMETERS
There are other solutions, though I think the above two solutions are best. 还有其他解决方案,尽管我认为上述两种解决方案是最好的。 For example, your main program can copy the parameters to the
checkargs
module like this: 例如,您的主程序可以将参数复制到
checkargs
模块,如下所示:
# myapp.py
import checkargs
checkargs._PARAMETERS = _PARAMETERS
...
You could also have checkargs
directly reference the value in your main module, but that requires a circular import. 您也可以让
checkargs
直接引用主模块中的值,但这需要循环导入。 Circular imports should be avoided. 应避免循环进口。
Why would it be defined? 为什么要定义它? It's from a different module.
它来自其他模块。 Inside checkargs.py, you'd need to do:
在checkargs.py中,您需要执行以下操作:
from myapp import _PARAMETERS
However: 然而:
_
then, since that implies private/protected variables. _
命名,因为这意味着私有/受保护的变量。 myapp
into the checkargs
functions instead of importing it there. myapp
传递到checkargs
函数中,而不是将其导入那里。 If you don't, you're creating a circular import, which is logically terrible and doesn't actually work.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.