I have class Config() that loads configuration options. I create an instance of this class named cfg.
Then I have many classes A, B, C that have to read only members from cfg.
from mylib.config import *
from mylib.A import *
from mylib.B import *
from mylib.C import *
cfg = Config(filename)
a = A()
a.do_things()
and for instance in A constructor I have:
def __init__(self):
self.name = cfg.name
problem is that I get at runtime "NameError: name 'cfg' is not defined" on line self.name = cfg.name
I first thought it's something that I import mylib.A, mylib.B and mylib.C BEFORE declaring cfg so I moved
cfg = Config(filename)
before importing mylib.A...B...C. But still same error.
Possible solutions:
1. pass object 'cfg' as argument, but I would have to change signature for all methods in all classes A, B, C and I feel it's not clean since it multiplies same argument accross all methods.
2. create private member _cfg for classes A, B, C. Better but nor very nice again, data is multiplied
3. put class definition + instance declaration in one file, and import it in mylib.A, mylib.B and mylib.C : AFAISI it's best solution, but still not my taste because I mix class definition and instance declaration, and I like to have only class definitions in class files
4. to avoid class definition and instanciation in same file, I can create a 'init.py'
from mylib.config import *
cfg = Config(filename)
and then import init in mylib.A, mylib.B and mylib.C... but I already have an init file, with log functions and since Config constructor uses those function, it creates circular import issues (init.py is imported in mylib.config.py class declaration file, and mylib.config is imported in init.py), to avoid it I should have init.py and init_config.py for instance.
Isn't there anything better/cleaner/simplier ?