28th Oct 2021 6 minutes read How to Write a Custom Module in Python Xavier Rigoulet python module 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 function def 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 module import circle_area # Call the function print("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 function def area_of_circle(r): pi = 3.14 area = pi * (r * r) return area # Define a variable coolpy = "LearnPython.com is cool!" We then print it from our main.py file: # Import the circle_area module import circle_area # Call the function print("Area of circle = %.6f" % circle_area.area_of_circle(7)) # Print the variable print(circle_area.coolpy) This gives us the following output: Area of circle = 153.860000 LearnPython.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 class class 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 modules import circle_area import pypok # Call the function print("Area of circle = %.6f" % circle_area.area_of_circle(7)) # Print the variable print(circle_area.coolpy) # Call the class squirtle = 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.860000 LearnPython.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 function def 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 module import 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! Tags: python module