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.

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

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.

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:

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.

The result is the same as before.