Calling a Python Function Located in a Different Directory

Most of my Python language programs are relatively short (less than 500 lines of code) but every now and then I need to organize multiple files. There are several ways to call a Python function that is located in a different file from the calling statement. The easiest way in most cases is to place external functions into a module file (just an ordinary file with a .py extension) and then use the sys.path() function and import statement in the main calling file.

For example:

# demo_program.py

import numpy as np
import sys
sys.path.insert(0, "../Utilities")
import my_utilities as U

. . .


def main():
  s = U.log_sig(0.5)
  . . .

if __name__ == "__main__":
  main

This assumes there is a directory named Utilities which is up one directory from the current directory and which contains a file named my_utilities.py. The sys.path.insert tells the program to look for the Utilities directory first, before other directories just in case there’s an existing Utilities directory in the system path. Then the import statement uses the name of the module file but leaving off the .py extension.

Instead of importing all functions in the my_utilities module file, you can import just selected functions in the usual Python way:

from my_utilities import log_sig
. . .
s = log_sig(x)

I prefer to import everything and then use an import alias.

Every programming language has a way to organize modules. The general principles are always the same but the implementation details differ quite a lot from language to language.



From left: Ferrari Enzo, Bugatti Veyron, Aston Martin DB11, Alfa Romeo 8C. Beautiful imports but not very practical for day-to-day use.

This entry was posted in Miscellaneous. Bookmark the permalink.