-
-
Save cbarrett/527232 to your computer and use it in GitHub Desktop.
% cat main.py | |
from config import config, set_config, print_config | |
print "1: %s" % (config) | |
set_config({'hello': 'world'}) | |
print "3: %s" % (config) | |
print_config() | |
% cat config.py | |
config = None | |
def set_config(new_config): | |
global config | |
config = new_config | |
print "2: %s" % config | |
def print_config(): | |
print "4: %s" % config | |
% python main.py | |
1: None | |
2: {'hello': 'world'} | |
3: None | |
4: {'hello': 'world'} | |
Line 3 above should be {'hello': 'world'}. I have no idea why it's not. Anyone know? |
If you change from config import config, set_config
to import config
(and then update the calls to be config.set_config
, etc), then it works as you expect.
The trick is that each module (or in this case, file) has its own "global" scope. When you do from config import config
, that actually creates a copy of config.config
and places it in the current scope. If you do
import config
print config.config
then you're referencing the config in the other scope, and it does what you expect.
It's beyond import confusion. when you assign config with new_config you're replacing the old config with a new object id. To fix it do config.py like so:
config = {}
def set_config(new_config):
global config
config.update(new_config)
print "2: %s" % config
def print_config():
print "4: %s" % config
Just to be clear, I do not want to write:
config.config
I want to just be able to write config
and have it work. Thanks to Dan I think I at least know what the problem is now. :)
See Import confusion: http://effbot.org/zone/import-confusion.htm
Use
import config
print config.config
config.set_config("foo")
print config.config
Output:
None
foo