Created
August 16, 2010 16:31
-
-
Save cbarrett/527232 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
% 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? |
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. :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you change
from config import config, set_config
toimport config
(and then update the calls to beconfig.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 ofconfig.config
and places it in the current scope. If you dothen you're referencing the config in the other scope, and it does what you expect.