When using Python you will most likely come across personal functions you defined on your own and are not available from a public package. Normally you need to define every custom function you want to use every time you call your script because Python does not know your functions otherwise. This leads to several function definitions at the top of your script which can make your script very long. To avoid this, you can put all your personal functions in their own file and place those in the same directory!

Let´s say you have two custom functions, being Dissolve.py and Finder.py lying in a folder named My.Functions. After telling Python where this folder is located, Python treats it as a Python package. However, some steps are needed to set this up in Python:

  1. Create a folder called My.functions somewhere on your system. I recommend you organize your all your Python stuff in one central directory and put your My.functions folder right there.
  2. Create an empty file called __init__.py in your My.functions directory. This is needed to initialize this folder as a “package-folder” to Python.
  3. Drop your Python functions in My.functions as single .py files (e.g. Dissolve.py and Finder.py).
  4. Now we need to tell Python to check this directory on startup. This is done by adding this folder to the PYTHONPATH variable. See here how this is done for macOS, here for Linux and here for Windows.

Now let’s check if everything works. Open a terminal and type python. Now try to import a function using for example from My.Functions import Dissolve. If you get no error message, the import was successful. No you can add as many functions as you want to your custom directory and import it. If you want to import all at once you just need to run import My.Functions.

Patrick Schratz

Patrick Schratz

PhD Student at University of Jena

I have experience in working with all kind of image analysis, GIS software and programming languages such as R and Python. Currently I use statistical and machine learning methods to improve the understanding of forest decline within tree plantations in northern Spain.