Importing function from a file in Python

The process of importing a function from a file in Python is similar to importing modules. You have to create two files. Next, insert the definition of the function in one file and call the function from another.

Create a file with a function

Name the new file myfile.py and insert a function.

def myfunction(mystr):
    print('my_function works.')
    print('Message: ' + mystr)

Create the second file, in the same directory, let’s call it main.py, and import the file and make a function call.

import myfile

myfile.myfunction('Hello World!')

This code will generate the following message.

my_function works.
Message: Hello World!

Another way to import

Let’s import a file and call a function a bit differently. Instead of using import myfile, we use from myfile import *.

Now, you can call a function, without using the file name at the beginning of it.

from myfile import *

myfunction('Hello World!')

This way, the program will import all functions inside the file. In our case, there is only one function.

Import file from another location

Python 3.3+

If the file where you want to call a function is in a different location than the file you want to import, you have to use the SourceFileLoader class.

I have my second file called myfile2.py at this location: D:/myfile2.py.

The modified main.py file looks like this:

from importlib.machinery import SourceFileLoader
mymodule = SourceFileLoader('myfile2', 'D:/myfile2.py').load_module()

mymodule.myfunction2('Hello World!')

The class SourceFileLoader takes a path and loads a module using the load_module function. This module is assigned to the mymodule variable.

After you run the code, you will get this message.

my_function2 works.
Message: Hello World!

Python 3.5+

You can also import a file using the util module.

import importlib.util

spec = importlib.util.spec_from_file_location("myfile2", "D:/myfile2.py")
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
foo.myfunction2('Hello World!')

The result is the same as before.