Skip to content

Instantly share code, notes, and snippets.

@cbarrett
Created August 16, 2010 16:31
Show Gist options
  • Save cbarrett/527232 to your computer and use it in GitHub Desktop.
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?
@rincewind
Copy link

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

@bjhomer
Copy link

bjhomer commented Aug 16, 2010

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.

@danimal
Copy link

danimal commented Aug 16, 2010

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

@cbarrett
Copy link
Author

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