A Python module is nothing but a Python file or a set of Python files. With Python modules, you can write reusable and more organized code. For instance, you can write a generic Python module that performs CSV file handling tasks and this module can be used by data scientists around the world to read, write, and manipulate CSV files.

Python comes with hundreds of default modules that provide different functionalities. However, you can also write your own custom modules in Python. That’s what we’re going to teach you in this tutorial.

Creating a Custom Python Module

To create a custom module in Python, all you have to do is create a new Python file. Let’s see this with the help of an example. Create a Python file named newmodule.py with the three functions: print_text(), find_log(), and find_exp(), as shown below. Since a module is just another Python file, you can define anything inside a Python module, like classes, methods, data structures and more.

newmodule.py

import numpy as np

def print_text():
    print("This message is from an external module")


def find_log(num):
    return np.log(num)

def find_exp(num):
    return np.exp(num)

That’s it! Congratulations, you just created a module named newmodule. You can use the three functions you defined inside newmodule in your other Python applications and files. But how do you do that?

To use a custom Python module, your Python interpreter should be able to access the Python file containing your custom module. There are three locations where you can save your Python file containing your custom module so that it is accessible by the Python interpreter.

  1. Within the same directory as the Python file accessing the modules
  2. Within another directory which has to be added in the path of your Python interpreter
  3. Within one of the default paths for your Python interpreter.

Code More, Distract Less: Support Our Ad-Free Site

You might have noticed we removed ads from our site - we hope this enhances your learning experience. To help sustain this, please take a look at our Python Developer Kit and our comprehensive cheat sheets. Each purchase directly supports this site, ensuring we can continue to offer you quality, distraction-free tutorials.


Importing Custom Modules within the Same Directory

Create another file called mainfile.py within the same directory where you created your newmodule.py file. The mainfile.py file will be used throughout this tutorial to test functions from your custom modules.

To import a custom module, you can use the import statement followed by your module name. This syntax is similar to importing default or installed Python modules. The script below imports the newmodule module which is created by the newmodule.py file stored in the same directory as the mainfile.py file. It’s important to mention that to import a module, you only have to specify the module name, without the “.py” extension.

Next, the script calls the three functions defined inside our newmodule module. One way to call a function from another module is to specify the module name, followed by the dot “.” operator, and the function name, as shown in the script below:

mainfile.py

import newmodule

newmodule.print_text()

print("This message is from the main file")

log16 = newmodule.find_log(16)
print(log16)

exp16 = newmodule.find_exp(16)
print(exp16)

The above script should execute successfully and you should see the following output, which shows that you were able to successfully import the newmodule module.

Output:

This message is from an external module
This message is from the main file
2.772588722239781
8886110.520507872

If you get tired of typing out a long module name followed by a dot operator, you can give your module an alias when importing it via the as operator, like this:

mainfile.py

import newmodule as nm

nm.print_text()

print("This message is from the main file")

log16 = nm.find_log(16)
print(log16)

exp16 = nm.find_exp(16)
print(exp16)

Output:

This message is from an external module
This message is from the main file
2.772588722239781
8886110.520507872

Notice how instead of typing newmodule each time you want to call a function, you now just type nm.

If you know you’ll only be needing a function functions from a module, you can make it even simpler by importing those specific functions or features from your module instead of importing the complete module. To do so, you can use the from keyword. For instance, the script below imports the find_log() function from the newmodule module. In this case, you don’t need to append the function name to the module name using the dot operator at all! Rather, you can directly call the function name.

mainfile.py

from newmodule import find_log

log16 = find_log(16)
print(log16)

Output:

2.772588722239781

In the same way, you can import multiple functions from a module. For instance, the script below imports the find_log() and find_exp() functions from our newmodule module.

mainfile.py

from newmodule import find_log, find_exp

log16 = find_log(16)
print(log16)

exp16 = find_exp(16)
print(exp16)

Output:

2.772588722239781
8886110.520507872

There’s an even easier way to avoid the dot notation, though. If you want to import everything from a Python module, simply use the asterisk, *, operator. This way, you can use all the functions, classes and more from a module without appending that functionality to the module name using a dot operator. Here’s an example.

mainfile.py

from newmodule import *

log16 = find_log(16)
print(log16)

exp16 = find_exp(16)
print(exp16)

Output:

2.772588722239781
8886110.520507872

Importing Custom Modules from a Different Path

You can also save your custom module in a directory other than the one in which it’s being imported. Let’s create another module using the Python file newmodule2.py. The file contains one method find_sqrt() as shown below.

newmodule2.py

import numpy as np

def find_sqrt(num):

    return np.sqrt(num)

Let’s save the above file in a different direct. We’re going to use “C:\Datasets” here.

Now, if you want to import the newmodule2 module in your Python application, you will have to append the path of the module to the list of paths accessible to your Python interpreter. The sys.path list contains the list of these paths.

You can use the append() method to add a new path to the list of the paths accessible to your Python interpreter. After that, you can import the module and access its functions. Here’s an example script for your reference.

mainfile.py

import sys
sys.path.append(r"C:\Datasets")

import newmodule2

sqrt16 = newmodule2.find_sqrt(16)
print(sqrt16)

Output

4.0

Code More, Distract Less: Support Our Ad-Free Site

You might have noticed we removed ads from our site - we hope this enhances your learning experience. To help sustain this, please take a look at our Python Developer Kit and our comprehensive cheat sheets. Each purchase directly supports this site, ensuring we can continue to offer you quality, distraction-free tutorials.


Adding and Importing Custom Modules from a Default Python Path

Finally, you can import a custom module into your Python application by saving the module in one of the default paths that the Python interpreter searches when it tries to import Python modules.

To see the list of these paths, you can iterate through the “sys.path()” lists, as shown in the script below:

import sys
for i in sys.path:
    print(i)

Note: Your output will be different depending on your Python installation and system name.

Output:

C:\Users\usman\anaconda3\python38.zip
C:\Users\usman\anaconda3\DLLs
C:\Users\usman\anaconda3

C:\Users\usman\anaconda3\lib\site-packages
C:\Users\usman\anaconda3\lib\site-packages\win32
C:\Users\usman\anaconda3\lib\site-packages\win32\lib
C:\Users\usman\.ipython
C:\Datasets

You can add your custom module in any of the paths that exist in the sys.path list. A lot of people like to store their custom modules in the directory containing, site-packages. This directory is “C:\Users\usman\anaconda3\lib\site-packages” in our output above.

Let’s create another module named newmodule3.py and store it in your site-packages folder. Our newmodule3 module is going to look like this:

newmodule3.py

def find_product(num1, num2):
    return num1 * num2

The following script imports the newmodule3 module and executes the find_product() function from the module.

mainfile.py

import newmodule3

prod85 = newmodule3.find_product(8,5)
print(prod85)

Output:

40

Finally, you can import multiple custom modules from different locations in your Python application. As an example, the script below imports the newmodule, newmodule2 and newmodule3 modules that you created in this tutorial.

mainfile.py

import newmodule, newmodule2, newmodule3

log16 = newmodule.find_log(16)
print(log16)

sqrt16 = newmodule2.find_sqrt(16)
print(sqrt16)

prod85 = newmodule3.find_product(8,5)
print(prod85)

Output:

2.772588722239781
4.0
40

That’s all there is to it! It’s a great practice to store functions you use frequently in their own custom modules so you don’t have to rebuild them each time you’re making a new Python script. This is a fantastic way to keep your code organized, condensed and easier for external users to understand. If you found this tip helpful, subscribe using the form below and we’ll give you our best tricks to help you get the most out of Python.


Code More, Distract Less: Support Our Ad-Free Site

You might have noticed we removed ads from our site - we hope this enhances your learning experience. To help sustain this, please take a look at our Python Developer Kit and our comprehensive cheat sheets. Each purchase directly supports this site, ensuring we can continue to offer you quality, distraction-free tutorials.