Skip to main content
Practice

How to Create Your Own Python Modules

In Python, it is possible to create and use custom modules.

In this lesson, we will learn how to create and utilize your own modules.


Creating a Module File

First, you need to create a file that will serve as your module.

For example, let's create a circle.py file that contains a function to calculate the area of a circle and a function to calculate the circumference of a circle.

Contents of circle.py
# Import math module to use the value of pi
import math

# Function to calculate the area of a circle
def get_circle_area(radius):
return math.pi * radius ** 2

# Function to calculate the circumference of a circle
def get_circle_circumference(radius):
return 2 * math.pi * radius

In the circle.py file above, we imported the math module to calculate the area of a circle with the get_circle_area function, and defined the get_circle_circumference function to calculate the circumference of a circle.


Importing the Module

Now, you can use the import keyword to load the circle.py file into another Python file.

How to use the circle module
# Import the circle.py module located in the same directory
import circle

# Store the area of a circle with radius 5 in the variable area
area = circle.get_circle_area(5)

# Store the circumference of a circle with radius 5 in the variable circumference
circumference = circle.get_circle_circumference(5)

# Print the area of the circle: 78.54
print(area)

# Print the circumference of the circle: 31.42
print(circumference)

When using import circle, the module needs to be in the same directory as the Python script that is calling it.

If your module file is located in a subdirectory called modules, you can import it by specifying the relative path, such as import modules.circle.

If the module file is located in a parent directory, you will need to use the sys module to add the module's path.

Importing a module from a parent directory
import sys

# Add the modules directory from the parent directory to the system path
sys.path.append("../modules")

# Import the circle.py module from the modules directory
import circle

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.