I have a large codebase where all settings & constants are stored inside a settings.py
file, that gets imported in various places. I want to be able to import an arbitrary .yml
file instead, with the filename given at run-time to the executable main.py
.
It's easy to change settings
to load a .yml
file; but of course I can't pass it an arbitrary filename from main
, such that it will remember wherever else that settings
gets imported.
I tried to think of a few solutions:
- Modify
main
so that the first thing it does is copy the arbitrary yaml file, into the default place the yaml file will be loaded from (ugly) - Import the settings in
main.py
, and change references fromimport settings
toimport main
(circular imports) - Use
os
to set an environment variableSETTINGS_FILE=some_file.yml
, that later gets read by thesettings
submodule (somewhat ugly...) - Refactor the entire codebase to pass around a
settings
class instead of a module (a lot of work)
I feel like I'm generally thinking of this all in a stupid way, and that there must be a better way (although I couldn't find anything by search)... what am I missing?
EDIT:
I had no idea but apparently this works...
$ cat settings.py
setting = 1
$ cat other_module.py
import settings
print(settings.setting)
$ cat main.py
import settings
print(settings.setting)
settings.setting = 2
import other_module
$ python main.py
1
2