Reputation: 503
For some Python project, I defined the default configuration in a config
module. Customization is allowed by sourcing a rc file into it using
config = imp.load_source('config', 'some_rc_file')
The rc file might redefine only a subset of the configuration variables, or even not at all, and I expect that variables which are not redefined would still exist as attributes of the config
module, with their default value. If load_source
is called from __main__
, everything goes well. However, if it is used within a package, the only variables 'left' in the module are those of the rc file.
There's a MWE here. direct.py
works as expected, but not indirect.py
.
|-- run.sh # runs python {,in}direct.py
|-- altconfig.py # the rc file, redefines (only) BAR
|-- config.py -> testimp/config.py # symlink to use by direct.py
|-- direct.py # calls load_source directly
|-- indirect.py # calls load_source via uses_config.py
`-- testimp
|-- __init__.py
|-- config.py # default config, defines FOO and BAR
`-- uses_config.py
What import logic am I missing?
Upvotes: 1
Views: 490
Reputation: 375484
If you add print(config)
to your test code, you'll see that the module imported by import config
is named config
, but the module imported by from . import config
in testimp is called testimp.config
. The first argument to load_source
is the name of the module to reuse. Since you are looking for config
, your existing import isn't found, and you get a new module object.
The simplest solution is to not hard code the name of the module. Change your imp lines to this, and it will work everywhere:
config = imp.load_source(config.__name__, 'altconfig.py')
Upvotes: 2