1

I want to define constants like BASE_DIR in a top level python file settings.py and access those constants from "all" files in my project, e.g. from import_scripts/import_users.py and export_scripts/export_users.py (Standalone helper scripts).

I tried a lot of different things like importing settings.py relative from import_users.py and import it in import_scripts/__init__py. No success so far.

Edit: I added the parent folder in my script e.g. in import_users.py to sys.path. But I don't want to do it in every script again and again so I was looking for a way to do it ONCE in my repository using a constant.

my_app
├── import_scripts
│   ├── import_users.py
├── export_scripts
│   ├── export_users.py
├── lib
│   ├── csv_reader.py
└── settings.py
herrjeh42
  • 2,782
  • 4
  • 35
  • 47
  • Use packages. You can import a package in a parent dir by `import .pkg_name`. – Diptangsu Goswami Sep 05 '19 at 10:49
  • Relative imports are relative within a package. As long as the entire tree is not a package you'd need to add the other (in this case parent) directory to `sys.path` or by other means manipulate where does your interpreter search for modules. – Ondrej K. Sep 05 '19 at 10:57
  • I added the parent folder e.g. import_users.py to sys.path. But I don't want to do it in every script again and again so I was looking for a way to do it ONCE in my repository. – herrjeh42 Sep 05 '19 at 11:00
  • you should import it. So don't use import statement but special function instead of: smth like [this](https://stackoverflow.com/questions/67631/how-to-import-a-module-given-the-full-path) – RandomB Sep 05 '19 at 11:04
  • Why not put `settings.py` in the `lib` directory from which you are presumably already importing things? – Davis Herring Sep 05 '19 at 14:57

1 Answers1

0

The importlib.util method here didn't work for me - the constants file I was trying to import isn't set up as a module (no __init__.py, etc). I also didn't want to add anything to my sys.path, as the file I wanted to import just contained settings for a particular machine learning run. Maybe not very elegant, but what I did was:

  1. Use the os module to store the current working directory as a variable
  2. Use the os module to build the path to the directory where the settings file is stored
  3. Use the os module to change directory to the location the settings file is located
  4. Import the settings variables
  5. Use the os module to change directory back to the current working directory

Sample code is here:

import os
cur_working_dir = os.getcwd()
run_settings_path = 'output/run_data/1'
path_to_settings_file = os.path.join(cur_working_dir,run_settings_path)
os.chdir(path_to_settings_file)
from settings_file import *
os.chdir(cur_working_dir)
Jeremy Matt
  • 647
  • 1
  • 7
  • 10