Creating Python Modules of Your Own

Introduction

Python modules play an important role in structuring and organizing code in Python projects. The previous lesson demonstrated how to import and use preexisting modules within your code. This lesson will explore how to create Python modules for organizing and reusing your code effectively.

Creating a Python Module

A module is just a regular Python code file. To build a Python module of your own, all you need to do is create a Python file in your project’s directory and give it a .py extension, as is normal for Python code files. Then the file will become available as a module named the same way as the file without the extension. It is conventional to give modules all lower-case names with words separated by underscore characters _.

Let’s see how this works. Suppose you create a file named area.py whose body is the code in the example below.

Example:

# area.py\

import math

def rectangle(width, height):
    return width * height
 
def circle(radius):
    return math.pi * radius**2

The module code above defines two functions, rectangle() and circle(), that calculate the area of a rectangle and circle, respectively. It imports the math module on line 3 in order to use the constant pi within circle(). Importing another module from within a module is possible since a module is regular Python code.

What we’ve just created is a module named area. Let’s see how we can use it.

Using Your Custom Module

Once you’ve written your module as described above, you can use it in other Python files that share the same directory. (Later lessons will discuss how to use modules placed in other directory using packages and path definitions.)

To use your module, you must import it with an import statement. The import as applied to custom modules has the exact same capabilities as any other import.

Example:

import area

width = 6
height = 7
print(f"The area of a rectangle of width {width} and height {height} is {area.rectangle(width, height)}.")

radius = 3
print(f"The area of a circle of radius {radius} is {area.circle(radius):.4f}.")

Output:

The area of a rectangle of width 6 and height 7 is 42.
The area of a circle of radius 3 is 28.2743.

The code in the example above imports the custom area module (line 1) and then calls its functions rectangle (line 5) and circle (line 8).

Summary & Reference for Creating Python Modules

A Python module serves as a means to structure and reuse code within projects effectively. By creating Python modules of your own, you can encapsulate functionality for reusability and maintainability.


To write a Python module, simply create a Python file in your project directory with a .py extension.


The module’s name is the same as the file name without the extension. Conventionally, modules have lowercase names with words separated by underscores.


To use your custom module in other Python files, import it using the import statement.