'Python - packages and settings file

I have a python package that needs to pull in settings from my project directory, here is how my project is currently structured:

~/Project/bin/mypackage
    - package files
    
~/Project/myproject/
    - project files
    - start.py
    - settings.py

I guess it's similar to how Django is structured, you have a settings.py file in your project directory that is somehow referenced by the Django system package in your Python directory.

So, if I am running start.py like so:

python ~/Project/myproject/start.py

..and start.py imports and utilizes the mypackage package, is there any way I can reference the settings.py file local to start.py from within the package? Would I have to load the settings file in start.py and store the values in a global? Does anyone know how this is possible?



Solution 1:[1]

The way I see it you have several options:

  1. look for settings and import them either from the current working directory or as determined from environment variables. This is the "django way" using DJANGO_SETTINGS_MODULE and PYTHONPATH. This is nice and magical when it works and inconvenient when it doesn't such as in your case when you are running from a different directory.

  2. rely on module search path which will include the directory of the calling package. Nice and simple but the settings will vary based on the caller. For example all you need in mypackage is:

    import settings

  3. pass in settings as a variable

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 djvg