0

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:

  1. 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)
  2. Import the settings in main.py, and change references from import settings to import main (circular imports)
  3. Use os to set an environment variable SETTINGS_FILE=some_file.yml, that later gets read by the settings submodule (somewhat ugly...)
  4. 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
  • Why not triggering the loading of the YAML file in `main` and then put it in a variable in `settings`? – flyx Jul 22 '21 at 15:27
  • @flyx Oh my goodness, I had no idea you could do this. So once `settings` is modified within `main`, if it is imported in another module (itself imported by main), the modifications to `settings` made from within `main` still remain. I guess importing it from the other module doesn't trigger a true "reimport"...? Thanks, didn't realise that...! – Euan Richard Jul 22 '21 at 16:15
  • [See here](https://stackoverflow.com/questions/19077381/what-happens-when-a-module-is-imported-twice) – flyx Jul 23 '21 at 09:19

0 Answers0