Monday, 1 April 2019

python settings for a project - circular imports / dependency injection

I've created a 'django style' settings files for different environments. The settings files define some variables, and also serves as a dependency injection for other modules.

So the structure is:

settings/
    ___init__.py
    base.py
    dev.py
    dev2.py
    prod.py

service/
    __init__.py
    service.py
    service_mock.py

And in settings/__init__.py I write:

settings_env = os.environ.get('PROJECT_SETTINGS', '')
if settings_env == 'prod':
   from .prod import *
elif settings_env == 'dev':
   from .dev import *

Each settings file define different some variables, and also import a class from service.py or service_mock.py, depends on the environment variable.
This works mostly fine.

Now, the problem is that the service.py cannot import the settings package, because the settings files import the service.py, so that will become a circular import.

As I see in django it is solved by using import strings in the settings files, instead of actual imports. I don't really like the idea as I lose some of the IDE autocomplete features, also I'm not sure how to actually create the settings object that django provides.

What are the solutions to this problem? Having a settings file that serves as a dependency injection container that import modules, and get imported by the same modules? Preferably a simple solution.



from python settings for a project - circular imports / dependency injection

No comments:

Post a Comment