Problem
Many people say their variable-sharing problems are resolved with the approach provided here and here, but neither of them works in my use case, where all configurations have to be written in a class like following.
# config.py
class Config(object):
var = None
The structure of my project looks like
├── config.py
├── main.py
├── subfolder
| ├── change_config.py
In this project, main.py
will invoke change_config.py
and they both have access to variables defined in config.py
. Importantly, change_config.py
will modify the variables (aka., var
) whose value is only known during runtime.
But it is not clear how I should share the instantiated Config()
(aka. opt
) across main.py
and change_config.py
. I tried following but no luck. The issue is
- If I instantiated another
Config()
inchange_config.py
, the one inmain.py
will be wiped out. - If I do not do the first one, then name
opt
would not be resolved inchange_config.py
# main.py
import config
from subfolder import change_config
opt = config.Config()
print(opt.var)
change_config.change_config()
print(opt.var)
# change_config.py
import config
def change_config():
opt.var = 10
More information
If I run main.py
, then I will have
NameError: name 'opt' is not defined
which is expected since opt
is never declared in change_config.py
.
If I change change_config.py
into
# change_config.py
import config
opt = config.Config()
def change_config():
opt.var = 10
where I declared another opt
. There is no error but returned
None
None
which is also expected since opt
declared in main.py
is wiped by the one in change_config.py
. But the expected output should be
None
10
So the question is how to share opt
in main.py
with change_config.py