How to Write a Custom Module in Python (2024)

Do you wonder how you can write your own Python custom module, similar to famous Python libraries such as NumPy or Pandas?

In my previous article for LearnPython.com, we learned about custom classes in Python. With Kateryna’s article on Python functions, you now have the required knowledge to implement your own custom module in Python.

If you are still wondering why you should learn Python in 2021, check out Rebecca’s excellent article on the topic.

In this article, we explore what a Python custom module is, and how to write a module in Python. Let's get right into it.

What Is a Custom Module in Python?

A module is a Python program file composed of definitions or code you can leverage in other Python program files. They are the .py files written in Python.

You can write a Python module yourself. They can contain definitions of function, classes, and variables that can be used in other Python programs.

Why Write a Custom Module in Python?

Writing custom modules in Python is helpful for breaking down large parts of a program into smaller, more manageable, and organized files. It also increases the code reusability and is an excellent application of the DRY (Don’t Repeat Yourself) principle.

For example, instead of copying and pasting the functions we use into different programs over and over again, we can store them in a Python custom module and import them as needed.

How to Write a Custom Module in Python

Let's run a quick example by writing a module called circle_area. It is saved as circle_area.py and contains a function to calculate the area of a circle:

# circle_area.py# Define a functiondef area_of_circle(r): pi = 3.14 area = pi * (r * r) return area

Then, we open another file called main.py in which we run our function, like this:

# main.py# Import the circle_area moduleimport circle_area# Call the functionprint("Area of circle = %.6f" % circle_area.area_of_circle(7))

Because we are referencing a module, we need to call the function by referencing the module name in dot notation. For more information, you can see Kateryna’s article on Python functions.

When we run the main.py script in the console, we get the following output:

Area of circle = 153.860000

We have imported the whole module in the example above. Alternatively, we could have only imported the functions needed for our program. In this case, we would import just the area_of_circle() method as:

from circle_area import area_of_circle

We can also import a module by renaming it:

import circle_area as ca

It can save typing time. Abbreviations often become standard practice in the industry; for example, the NumPy library is often imported as np.

We can also import all the definitions from a module with the asterisk (*) symbol, like so:

from circle_area import *

However, it is not a good programming practice, as it can lead to duplicate definitions and make the code less readable.

We can also define variables within the module and call them from our main script. For example, I have updated the previous circle_area.py module by adding a variable called coolpy:

# circle_area.py# Define a functiondef area_of_circle(r): pi = 3.14 area = pi * (r * r) return area# Define a variablecoolpy = "LearnPython.com is cool!"

We then print it from our main.py file:

# Import the circle_area moduleimport circle_area# Call the functionprint("Area of circle = %.6f" % circle_area.area_of_circle(7))# Print the variableprint(circle_area.coolpy)

This gives us the following output:

Area of circle = 153.860000LearnPython.com is cool!

Building upon my previous article on how to write a custom class in Python, we can also add classes to our custom Python module. For clarity, I have created a new module saved as pypok.py, which contains the Pokemon class I used previously:

# pypok.py# Define a classclass Pokemon: def __init__(self, power, level, names): self.power = power self.level = level self.names = names def __repr__(self): return (f'Pokemon({self.power}, ' f'{self.level}, ' f'{self.names})') def total_damage(self): return self.damage(self.power, self.level) @staticmethod def damage(power, level): return (power * level * 2) / 50

We now add the class to main.py. For the script to run without error, I need to import my new pypok module.

# main.py# Import the circle_area and pypok modulesimport circle_areaimport pypok# Call the functionprint("Area of circle = %.6f" % circle_area.area_of_circle(7))# Print the variableprint(circle_area.coolpy)# Call the classsquirtle = pypok.Pokemon(20, 8, "Squirtle")print("Squirtle inflicts", squirtle.total_damage(), "points of damage!")

Running our main.py script returns the following output:

Area of circle = 153.860000LearnPython.com is cool!Squirtle inflicts 6.4 points of damage!

Once we have called the custom class previously defined, we can access the functions and attributes of the class within the main.py file’s namespace.

While we can write custom modules to define functions, we can also write them to implement code.

# circle_area.py# Define a functiondef area_of_circle(r): pi = 3.14 area = pi * (r * r) return area# Call the function inside the module print(area_of_circle(7))

We update the main.py script by deleting everything except the module import line:

# main.py# Import the circle_area moduleimport circle_area

Now, we can run the script and get the following output:

153.86

As you can see, one line of import in our main.py file is enough to get the output. While this indeed works, you should avoid such solutions. Imports shouldn't do anything more than letting Python know about new objects. After all, you don't want to perform heavy calculations before they are needed.

It is better to keep the modules as general as possible to make them reusable and to avoid repeating ourselves. The project-specific variables should be kept in the general file, like main.py.

Write Custom Modules in Python!

I hope this article has given you a good understanding of how to write a module in Python. Do not hesitate to play with the snippets above and write your own modules.

Also, I encourage you to reflect on your programming practice. Which functions or classes do you use frequently? It can be a good practice to store them in your Python custom module to save time and make your code more readable and easier to maintain.

If you are looking for a list of online Python resources, Dorota has your back with her list of online resources for learning Python. Last but not least, if you want to learn more about all this and improve your Python skills, check our Python programming track. It gives you a roadmap to help you achieve your goals faster!

How to Write a Custom Module in Python (2024)

FAQs

How do you create a custom module in Python? ›

Creating a Custom Python Module

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. That's it!

How do you write a Python module? ›

To create a module just save the code you want in a file with the file extension .py :
  1. ExampleGet your own Python Server. ...
  2. Import the module named mymodule, and call the greeting function: ...
  3. Save this code in the file mymodule.py. ...
  4. Import the module named mymodule, and access the person1 dictionary:

Do you need __ init __ py in Python 3? ›

Since version 3.3 and the implementation of PEP 420, Python will automatically create “Namespace Packages” implicitly in many cases. This means that __init__.py is now often optional, but it's still useful to structure your initialization code and define how statements like from mypackage import * should work.

What is an example of a Python module? ›

A file containing Python code, for example: test.py , is called a module, and its name would be test . There are various methods of writing modules, but the simplest way is to create a file with a . py extension which contains functions and variables.

Can we create custom module? ›

Answer. Custom modules can be used to organize or display content in ways not possible using the default Participate content modules. For example, you can create a module that uses more fields than those allowed in the standard content modules.

How do I add a custom module? ›

There are two steps required to create your own custom module: (1) write a module file and (2) add a line to your ~/. bashrc file to update the MODULEPATH. The example module file above (with filename 1.2) sets two environment variables and loads two system modules. Module files are written in the Tcl language.

What is __ init __ in Python? ›

In Python, __init__ is an instance method that initializes a newly created object. It takes the object as its first argument followed by additional arguments. The method takes the object as its first argument (self), followed by any additional arguments that need to be passed to it.

Why does Python 3 exist? ›

Mistakes Were Made…

Python 3 exists because Guido saw areas of the language that needed some improvements and the changes couldn't be made with backward compatibility in mind.

Why can I use py but not Python? ›

You can see that Python is installed, but when you run the command: Python you cannot reach it while you can reach py. The reason is the command python does not set up the environment PATH correctly, while py does because py is itself located in C:\Windows that is always part of the PATH, which is why you found it.

Should I use __ all __ in Python? ›

So, using __all__ is a good way to limit wrong uses of your code. Here's a quick list of best practices for using __all__ in your code: Try to always define __all__ in your packages and modules. This variable provides you with explicit control over what other developers can import with wildcard imports.

What are common Python module names? ›

There are a lot of built-in modules in Python. Some of the important ones are - collections, datetime, logging, math, numpy, os, pip, sys, and time.

What are Python modules written in? ›

The library contains built-in modules (written in C) that provide access to system functionality such as file I/O that would otherwise be inaccessible to Python programmers, as well as modules written in Python that provide standardized solutions for many problems that occur in everyday programming.

How many modules are in Python? ›

The Python standard library contains well over 200 modules, although the exact number varies between distributions.

How do I create a custom module in PyCharm? ›

Open PyCharm and create a new project or open an existing project. In the project window, right-click on the folder where you want to create the module and select "New" > "Python File" from the context menu. In the "New Python File" dialog, enter a name for your module and click "OK".

What are custom modules? ›

There are four core modules– contacts, accounts, deals, and products– to create and track your sales process. In addition to these four modules, you can also create additional modules, or custom modules, that are relevant to your business process and capture additional information.

Top Articles
Latest Posts
Article information

Author: Duane Harber

Last Updated:

Views: 6019

Rating: 4 / 5 (71 voted)

Reviews: 94% of readers found this page helpful

Author information

Name: Duane Harber

Birthday: 1999-10-17

Address: Apt. 404 9899 Magnolia Roads, Port Royceville, ID 78186

Phone: +186911129794335

Job: Human Hospitality Planner

Hobby: Listening to music, Orienteering, Knapping, Dance, Mountain biking, Fishing, Pottery

Introduction: My name is Duane Harber, I am a modern, clever, handsome, fair, agreeable, inexpensive, beautiful person who loves writing and wants to share my knowledge and understanding with you.