Introduction
Real life applications can reach thousands of lines of code. That is why developers are in the need of tools to categorize their code.
The de facto standard to achieve it is called module. A module can export any type of object inside it, like functions and classes. In this article you are going to learn how to make a module in Python.
Creating modules
Python has some interesting conventions around, one of them is that importing a file automatically gives you access to all names of it, that is the foundation of creating modules, every file is a module when called.
To apply this we are creating a custom module, the code of has two functions, one for calculating the manhattan and other euclidean distance and one for a class called Point
, save it in a file called distances.py
:
import math
def euclidean(point1, point2):
x = point2.x - point1.x
x = x * x
y = point2.y - point1.y
y = y * y
return math.sqrt(x +y)
def manhattan(point1, point2):
x = point2.x - point1.x
x = math.fabs(x)
y = point2.y - point1.y
y = math.fabs(y)
return x + y
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
With this we can proceed to use it normally as any other module.
Using modules
As we do not want to mix the logic code with the implementation code, we are creating a new file called main.py
, in this file copy the next code:
import distances
point1 = distances.Point(7, 9)
point2 = distances.Point(-4, 8)
res1 = distances.euclidean(point1, point2)
res2 = distances.manhattan(point1, point2)
print('Euclidean distance: {}'.format(res1))
print('Manhattan distance: {}'.format(res2))
That program is importing our module, and using all of the code written on it without raising ay problem. Something important to note is that one has to use the dot notation to access any feature on it.
After having executed the main.py
file the output will look like this:
Euclidean distance: 11.045361017187261
Manhattan distance: 12.0
And with this we end this part of the article, feel free to experiment with diverse inputs in the main.py
file to affect the output file, just remember that input is not being checked, so any wrong input data and the program will fail to execute.
Conclusion
Create modules is really easy, with this one can focus on writing semantic code that solves a particular problem with the benefit of having a cleaner code. Modules also make sharing code easier, because of this it is important to learn how to do them, even though they are this easy.
After this part one should look at how to create a library and share to the people through pypi.