1

Let's say I have a python module called custom_colors.py in which I create some variables I am using in multiple projects in different working directories. So I am wondering what's the best practice of how to work with such helper files?

copy them into each project's folder?

So far I thought about creating a folder for all helper files like this and import whenever needed

import os
# change workding directory to helper files folder and load own modules
os.chdir(helper_files_path)
import utils.custom_colors as cc

but for this approach I always need to change the working directory first.

How do you guys handle such stuff?

Quastiat
  • 1,164
  • 1
  • 18
  • 37

1 Answers1

2

You keep them in a central location, but you don't make your script responsible for finding that location. Instead, you tell the interpreter where it is by using PYTHONPATH.

import os
import utils.customer_colors as cc

...

If the path to your module is something like /path/to/lib/utils.py, then run Python with

PYTHONPATH=/path/to/lib python myscript.py

You can add this change to your environment so that you Python will always look in /path/to/lib when searching for a module.

Taking this one step further, package your library so that you can install it using python setup.py install or pip install mylib, then create a virtual environment for each project and install mylib in the virtual environment.

chepner
  • 497,756
  • 71
  • 530
  • 681