<img alt="How to Create a Custom Module in Python" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/How-to-Create-a-Custom-Module-in-Python.jpg/w=800" data- decoding="async" height="420" src="data:image/svg xml,” width=”800″>

Python is often referred to as a ‘batteries included’ programming language. This is due to its philosophy of including a wide range of inbuilt modules and packages, thus providing a comprehensive standard library to perform a wide range of tasks.

A Python module is a file containing Python statements and definitions such as variables, functions, classes, or methods. Usually, it has a .py extension, and the name of the file is also the name of the module.

Python Modules

Python modules usually contain code that performs specific tasks. A package, on the other hand, is simply a collection of Python modules.

Python modules power modular programming in Python, allowing large projects and tasks to be broken down into smaller manageable parts or modules that can later be brought together to create a much larger application. Although Python comes with a lot of inbuilt modules, users can also create their own modules.

<img alt="python-programming" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/python-programming.jpg/w=998,h=630" data- decoding="async" height="630" src="data:image/svg xml,” width=”998″>

An example of a commonly used module is the math module which provides access to mathematical functions such as factorial(), ceil(), floor(), sqrt(), and pow() among many others.

In case you want to calculate the power or the square root of numbers, you don’t need to write the logic to do that yourself. You simply import the Python module that contains code with that functionality. In this case, you need the math module. After importing the module, you can access the function you need as shown below:

import math

print("Using the math module to perform mathematical calculations")
print(math.pow(3, 2))
print(math.sqrt(100))

Output:

Using the math module to perform mathematical calculations
9.0
10.0
<img alt="Python-math-output" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/Python-math-output.png/w=720" data- decoding="async" height="198" src="data:image/svg xml,” width=”720″>

Python modules are very useful in code organization and code reusability. Python modules allow you to logically organize and group related code together, which makes your code easier to understand and use.

Modules also make it easier to manage and maintain code, particularly in large Python projects with thousands of lines of code. You can easily manage the code base by grouping your code into modules, each with its own functionality

Another key feature of Python modules is that they allow for code reusability. For instance, if you are working on Python projects that use mathematical functions, you don’t need to keep rewriting the implementation of the functions in every project you work on.

All you need to do is store all the mathematical functions you need in a module, then import the module anywhere you need to use the functions. This is essentially what has been done with the math module used in the example above.

Custom Modules in Python

A custom module in Python is a module that you create on your own. Unlike inbuilt modules such as math, numpy, and pandas, which come with Python, a custom module is created by a user usually to perform a certain function or address a need in a project they are working on.

<img alt="python" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/python.png/w=833" data- decoding="async" height="384" src="data:image/svg xml,” width=”833″>

Creating your own custom module allows you to write reusable code that is clear to read and understand. It also makes it easier to organize large Python projects by breaking them down into smaller modules, each performing its own function. This makes managing and maintaining your Python project less hectic, even for a developer who did not work on the project.

When working in a team, custom modules also come in handy as developers can work on different modules at the same time and then later combine their modules into one big project.

This essentially allows developers to each work on different features in a project, resulting in shorter delivery times. Custom modules also make it easier to share code between different projects.

Modular development of projects through custom modules also makes it easy to scale projects by adding new modules to extend a project’s functionality and add new features. Testing and debugging are also easier when modules are used, as different modules can be tested in isolation, which is much easier and faster, and debugging is also less cumbersome.

<img alt="python interview questions" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/python-interview-questions-1.jpg/w=1200" data- decoding="async" height="630" src="data:image/svg xml,” width=”1200″>

Custom modules also allow you to abstract the implementation details of different functionalities in your code. This way you only need to expose interfaces to the rest of the program.

This can even be seen in inbuilt modules where you can work with a function, such as math.pow(), without having to know how the function is actually implemented.

Considering how beneficial custom modules are, it is important to know how to create your own custom module. Let us look at how you can create your own custom modules in Python.

Prerequisites

To start creating your own Python module, first, ensure you have Python installed on your machine and you have a text editor or integrated development environment (IDE) where you can write your code.

It is also required that you have an understanding of fundamental Python concepts such as how to work with variables, different data types, functions, classes, and control structures. Additionally, you should also be conversant with Python’s naming conventions.

Creating a Custom Python Module

To learn how to create custom modules in Python, let us create a module to help us work with days of the week. The module should allow us to get a random day of the week, get all the days in a week, check to see if a day is a weekend or a weekday, and also confirm if a string is a valid day of the week. To create this module:

1. Create a new project folder, and inside the folder create a file called daysoftheweek.py

2. Open the file in a code editor and paste the code below:

import random
days = ['monday', 'tuesday', 'wednesday', 'thursday','friday', 'saturday', 'sunday']

# get random day of the week
def random_day():
  random_index = random.randint(0, len(days)-1)
  return days[random_index]

# get all the days in a week
def all_days():
  return days

# check to see if a day is a weekend or a weekday
def is_weekend(day):
  lowercase_day = day.lower()
  if(lowercase_day == 'saturday' or lowercase_day == 'sunday'):
    return True
  return False

# check if a string is a valid day of the week
def is_day_valid(day):
  lowercase_day = day.lower()
  if lowercase_day in days:
    return True
  return False

The code above creates a custom module with four functions namely: random_day() to get a random day, all_days() to get all the days in a week, is_weekend() to check if a day of the week if a weekend of not, and is_day_valid() to confirm if a string is a valid day of the week. Once we’ve created this module, the next step is using it.

3. In the same folder, create another file called main.py and open it in an editor. main.py is where we are going to work with the module we created earlier

4. To start using the daysoftheweek.py module that we just created, in the main.py file, add the following line

import daysoftheweek

This line imports the daysoftheweek module into our main Python file, allowing us to work with all the functions described in the daysoftheweek custom module. Our entire daysoftheweek module will be loaded and made available in the file we are working in.

5. To test if the module works, let us generate a random day of the week, then check to see if it is a weekend or not. To do this, enter the code below in your main.py file then run the file. You can run it multiple times to get different outputs.

import daysoftheweek

# get random day of the week
rand_day = daysoftheweek.random_day()

# check if the random day is a weekend or not
is_weekend = daysoftheweek.is_weekend(rand_day)

print("Random day of the week generated: "   rand_day)
print("Is it a weekend?:"   str(is_weekend))

Output:

Random day of the week generated: sunday
Is it a weekend?:True
<img alt="random-day" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/random-day.png/w=716" data- decoding="async" height="204" src="data:image/svg xml,” width=”716″>

6. Instead of importing our entire custom module into the file we are working in, we can import only the functions we need. To do this, we use the following import syntax:

from  import 

In our case, to only import the is_day_valid() function, we use this line:

from daysoftheweek import is_day_valid

Using this syntax, we only import the is_day_valid() function from our custom module. All other functions in our custom module that we have not explicitly imported will not be available to us. You can test out the is_day_valid() function using the code below:

from daysoftheweek import is_day_valid

day = 'Friday'
greeting = "Hello"

print("Is "   day   " a valid day of the week?")
print(is_day_valid(day))

print("Is "   day   " a valid day of the week?")
print(is_day_valid(greeting))

Output:

Is Friday a valid day of the week?
True
Is Hello a valid day of the week?
False
<img alt="is-day-valid-1" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/is-day-valid-1.png/w=716" data- decoding="async" height="204" src="data:image/svg xml,” width=”716″>

7. We can also import our custom module using an alias. That is, giving our module some sort of a nickname that we can use to access the module. To do this, we use the as keyword as shown below:

import daysoftheweek as week

Once we’ve imported the module using an alias, we use the alias, in our case week, to access functions and variables in the module. An example of this is shown below:

import daysoftheweek as week

days_of_week = week.all_days()

# Loop through the days and print them in uppercase
for day in days_of_week:
    print(day.upper())

Output:

MONDAY
TUESDAY
WEDNESDAY
THURSDAY
FRIDAY
SATURDAY
SUNDAY
<img alt="days-of-the-week" data- data-src="https://kirelos.com/wp-content/uploads/2023/09/echo/days-of-the-week.png/w=709" data- decoding="async" height="199" src="data:image/svg xml,” width=”709″>

Conclusion

Modules are a very useful tool in a programmer’s toolbox. Modules allow you to organize your code and write code that is readable, reusable, and easy to manage and maintain. In case you find yourself needing to rewrite the implementation of various functionalities in your Python projects, you should consider creating custom modules.

This should also be the case when you want to break down a large task or program into smaller manageable sub-tasks. Happy Coding!

You may also learn about Python libraries and modules every developer should know.