How to share globals between imported modules?

拜拜、爱过 提交于 2019-12-23 15:46:20

问题


I have two modules, a.py and b.py. I want the globals from a.py to be available in b.py like this:

a.py:

#!/usr/bin/env python
var = "this is global"
import b
b.foo()

b.py:

#!/usr/bin/env python
var = "this is global"
def foo():
    print var

Currently, I re-declare the globals in each module. There must be an easier way.


回答1:


Create a settings module that has shared globals if that's what you want. That way you're only importing and referencing each global one time, and you're keeping them isolated within the namespace of the settings module. It's a good thing.

#settings.py
var = 'this is global'

# a.py
import settings
import b
b.foo()

# b.py
import settings
def foo():
    print settings.var



回答2:


By making b.py require globals from a.py, you have created classes that depend on each other, which is bad design.

If you have static variables that need to be shared, consider creating c.py which both a.py and b.py can import and reference.

If you have dynamic variables that need to be shared, consider creating a settings class that can be instantiated and passed between the modules.




回答3:


Define your globals in c.py and import them into a.py and b.py



来源:https://stackoverflow.com/questions/7743905/how-to-share-globals-between-imported-modules

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!