Write your first python module

If you are planning to build a mid to enterprise size project/product then you should consider object oriented coding practice. This benefits in many ways. For eg, your code remains tidy and you can reuse components of your code in other projects.

Module is essentially a collection of several classes and class functions. These functions can be used/reused in many of your programs/projects. Typically python modules are installed at predefined path of operating system. To see default paths you can use following on python3 prompt.


>>> import sys

>>> print(sys.path)
['', '/usr/lib/python37.zip', '/usr/lib/python3.7', '/usr/lib/python3.7/lib-dynload', '/home/manish/.local/lib/python3.7/site-packages', '/usr/local/lib/python3.7/dist-packages', '/usr/lib/python3/dist-packages']

You can write your own modules in other directory paths as well, but then you should add those paths in default paths or refer modules with absolute path of module.

For better understanding let us write a small module, which has one class and four basic arithmetic functions. Each function accepts two arguments. Create a directory module in your home directory and in module directory create a python class file mkacalc.py with four functions in mkaops class.


#!/usr/bin/python3
# mkacalc.py

class mkaops:
        "This class has simple math functions with two parameters"
        def mkasum(self, x, y):
                print("Add", x, y)
                return x + y

        def mkadiff(self, x, y):
                print("Minus", x, y)
                return x - y

        def mkamult(self, x, y):
                print("Multiply", x, y)
                return x * y

        def mkadiv(self, x, y):
                print("Divide", x, y)
                return x / y

Now, this module is ready for use in other python programs. Let us try to call mkaops class of mkacalc module in testmod.py program in home directory. Here mkacalc is referred by module.mkacalc since mkacalc.py is within module directory.


#!/usr/bin/python3
# testmod.py

from module.mkacalc import mkaops

#Construct a new object of mkaops class
newobj = mkaops()

# Refers to class documentation
print(newobj.__doc__)

# Use mkaops class functions 
print(newobj.mkasum(5, 9))

print(newobj.mkadiff(38, 5))

print(newobj.mkamult(45, 9))

print(newobj.mkadiv(90, 6))

Output:


./testmod.py 
This class has simple math functions with two paramters
Add 5 9
14
Minus 38 5
33
Multiply 45 9
405
Divide 90 6
15.0

Tree structure of module and testmod.py looks like:


$tree .
.
├── module
│   └── mkacalc.py
└── testmod.py