[英]Import a single global variable from a different module in python
I have an interesting application and I would like to access a global variable from a different module. 我有一个有趣的应用程序,我想从其他模块访问全局变量。
I currently have module x 我目前有模块x
from pkg.mod import *
in order to get the namespace foo
. 为了得到命名空间
foo
。
where my pkg.mod looks like the following 我的pkg.mod如下所示
import x
foo = 0
# do some stuff
foo = myClass()
That all works just great, however, I would like NOT to do that, mostly just because its bad. 一切都很好,但是,我不想这样做,主要是因为它不好。
If I try the following 如果我尝试以下
from pkg import mod
I get a circular dependency issue. 我遇到了循环依赖问题。
ImportError: cannot import name mod
which makes sense to me. ImportError: cannot import name mod
对我有意义的ImportError: cannot import name mod
。
What I want to do is 我想做的是
from pkg.mod import foo
but that also gives me an import name error: ImportError: cannot import name foo
Which I am not exactly sure why, except I dont think you can import variables specifically. 但这也给了我一个导入名称错误:
ImportError: cannot import name foo
我不确定为什么,但我不认为您可以专门导入变量。
Is there anyway to import foo
following correct practices? 无论如何,是否遵循正确的做法导入
foo
?
---edit--- - -编辑 - -
I have tried to remove the shared variable and put it in a third module in such a way 我试图删除共享变量,并以这种方式将其放在第三个模块中
pkg.y 公斤
foo = 0
pkg.mod pkg.mod
from pkg.y import foo
foo = myClass()
x.dostuff()
x X
from pkg.y import foo
def dostuff():
print(foo)
and now x thinks foo is still 0. (I can guarantee that mod is calling x, and thus happening first.) 现在x认为foo仍然为0。(我可以保证mod正在调用x,因此首先发生。)
When I need a true global variable I find it cleaner to create a module called trueglobals.py; 当我需要一个真正的全局变量时,我发现它更干净,可以创建一个名为trueglobals.py的模块; it can remain empty but for proper documentation...
它可以保留为空,但用于适当的文档...
# -*- coding: utf-8 -*-
# Object references that are used extensively across many modules are
# stored here.
# someObject1 - instantiated in main.py
# someObject2 - instantiated in someothermodule.py
In the module instantiating the object... 在实例化对象的模块中...
import trueglobals
trueglobals.someObject1 = myClass(somevar)
In any module requiring the object... 在任何需要对象的模块中...
import trueglobals
localVar = trueglobals.someObject1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.