1

I have an application and currently it's set so one of the scripts config.py reads data from a config.yaml configuration file and also sets some defaults. This works nicely thus far as everything is defined in one place.

I now want to pass the application arguments from the CLI. How would I do this so I can also replace arguments in the config.py? I am likely structuring the application suboptimally, so any feedback is appreciated.

enter image description here

I see an extensive post on this here: Most Pythonic way to provide global configuration variables in config.py?

I am currently following the top simple "conventional" approach mentioned, i.e.:

config.py

MYSQL_PORT = 3306
MYSQL_DATABASE = 'mydb'
MYSQL_DATABASE_TABLES = ['tb_users', 'tb_groups']

Therefore global variables are imported in one of the following ways:

another_script.py

from config import MYSQL_PORT

Can I encapsulate everything in my config in an object or class without having to change all of the code importing from config.py.

aksg87
  • 63
  • 1
  • 9

2 Answers2

0

Define a Configuration object or class. Have your application read from the configuration object. Then you can have defaults in an external file and then parsed, or passed via CLI.

im_baby
  • 912
  • 1
  • 8
  • 14
  • I expanded my question a bit. My version 1 of the code is written as I explained. Now I want to expand to utilize a CLI without extensively changing the code base (if possible). Thank you! – aksg87 Feb 11 '21 at 03:29
  • I think that you should load the configuration in only one place, like application.py. After that, another_script.py doesn't read from config, but from the app object. Once you have that, you can initialize your app and update the config either from the CLI args, external file, or hard coded values in config.py – im_baby Feb 11 '21 at 18:20
0

After doing some research and talking to colleagues I came across this package which nicely solves this issue:

https://pypi.org/project/munch/

From the website:

Munch is a dictionary that supports attribute-style access, a la JavaScript:

>>> b = Munch()
>>> b.hello = 'world'
>>> b.hello
'world'
>>> b['hello'] += "!"
>>> b.hello
'world!'
>>> b.foo = Munch(lol=True)
>>> b.foo.lol
True
>>> b.foo is b['foo']
True
aksg87
  • 63
  • 1
  • 9