I'm in the following situation: I have a python script main.py, that runs some actions depending on a config file. The config file is a python script/class itself. I want to be able to pass different config files from the command line as parameter and import it in the main script.
Is it even possible in python to load classes dynamically? If so, how can I accomplish that task?
See the following minimal example for clarification.
This is my script main.py:
import argparse
def get_arguments():
parser = argparse.ArgumentParser(description="foo")
parser.add_argument("--configfile", required=True)
return parser.parse_args()
def main():
args = get_arguments()
from args.configfile import MyConfig # <-- how is that possible?
if MyConfig.SETTING1:
do_something()
if __name__ == '__main__':
main()
This is an example config.py:
class MyConfig(BaseConfig):
SETTING1 = True
SETTING2 = 1
This is another example config-special.py:
class MyConfig(BaseConfig):
SETTING1 = False
SETTING2 = 42
I'm calling it like this:
$ python3 main.py --configfile config.py
$ python3 main.py --configfile config-special.py