I have a class instance I want to access in other modules. This class loads config values using configParser to update an class instance __dict__
attribute as per this post:
I want to access this instance in other module. The instance is only created in the main.py
file where it has access to the required parameters, which come via command line arguments.
I have three files: main.py
, config.py
and file.py
. I don't know the best way to access the instance in the file.py
. I only have access to it in main.py
and not other modules.
I've looked at the following answers, here and here but they don't fully answer my scenario.
#config.py
class Configuration():
def __init__(self, *import_sections):
#use configParser, get config for relevant sections, update self.__dict__
#main.py
from config import Configuration
conf = Configuration('general', 'dev')
# other lines of code use conf instance ... e.g. config.log_path in log setup
#file.py
#I want to use config instance like this:
class File():
def __init__(self, conf.feed_path):
# other code here...
Options considered:
Initialise Configuration in config.py module
In
config.py
after class definition I could add:conf = Configuration('general', 'dev')
and in
file.py
andmain.py
:from config import conf
but the
general
anddev
variables are only found inmain.py
so doesn't look like it will work.Make Configuration class a function
I could make it a function and create a module-level dictionary and import data into other modules:
#config.py conf = {} def set_config(*import_section): # use configParser, update conf dictionary conf.update(...)
This would mean referring to it as
config.conf['log_path']
for example. I'd preferconf.log_path
as it's used multiple times.Pass via other instances
I could pass the conf instance as parameters via other class instances from
main.py
, even if the intermediate instances don't use it. Seems very messy.Other options?
Can I use Configuration as an instance somehow?