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
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:
- Create a folder called
My.functionssomewhere on your system. I recommend you organize your all your Python stuff in one central directory and put your
My.functionsfolder right there.
- Create an empty file called
My.functionsdirectory. This is needed to initialize this folder as a “package-folder” to Python.
- Drop your Python functions in
My.functionsas single .py files (e.g.
- 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
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.