I created a package in python. In the init file I placed a variable that must be available in all the modules of this package.
Example:
# main script
from _Framework.STB import DB
DB.environment = 'lab'
channel = DB.Channels.ChannelStatic.getChannelByNumber(416)
...
# Channels.py module in the package
from _Framework.DB.__init__ import cursor
from _Framework.DB.__init__ import environment
from time import *
...
The problem is that everdy call to
from _Framework.DB.__init__ import xy
overwrites my “global” variables
How can I solve?
Thanks
EDIT:
init.py:
all = [ 'Events', 'Channels', 'Genres', 'Subgenres','EPGSections']
try:
conn = MySQLdb.connect(host,user,passwd,db)
cursor = conn.cursor(MySQLdb.cursors.DictCursor)
except:
cursor = None
environment = 'live'
I import the DB package and I set the “environment” variable, but when the Channels module is imported, I think, it makes a new call to init.py and reexecutes its code so “environment” is overwritten. I’m looking for a clean way to share a variable between modules of the same package
I’m still not sure but if I understand correctly. YOu should just use the edit on your question and post correctly formatted code:
Now in Channels.py you want to change
_Framework.DB.__init__.cursorand_Framework.DB.__init__.environmentand this changes should be seen all around your program?If this is what you want you should know that when you do in a import:
What happens is that you get two variables cursor and environment in your Channels.py module namespace and any change you do will only be visible in that module. If you want to achieve your result try this:
This way you actually change the module variables. Now in the rest of your program, when you want to see the changes took effect you could either:
Acces the varibles in the same way you changed them:
import _Framework.DB
import like you did, BUT make sure the changes you want are done BEFORE you do any imports.
As an negative example for the second case:
Now if you are in this order of imports when you import A it will create a variable a in A’s namespace with the value of Vars.a. The Do_change will edit the variable accordingly, but A will have no knowledge of this. B however who is imported after will see the correct Vars.a = 2.
That’s why I really reccomend the first option as it is the correct approach in my opinion.