What is a python module? How to build your python module?

What is a python module? How to build your python module?

Modules can range from as small as a hello world program to a complex project that uses a lot of modules. Modules are of two types and each of them is explained below in detail. Also, we have covered how to build a basic Python module(s) with an appropriate use case to show its scalability.


Introduction?

A module in Python programming language is a filename with .py an extension. In technical terms, we can utilize the block of code, variables, and other accessible content written on that particular file(module). There are various 3 different ways to access a module in python which are described ahead in the blog.


Types of python modules ?️

Inbuilt Modules

These are modules that are readily available for us to work with. It’s been pre-installed as when we installed python. A few of them are os, platform, requests, math, etc. You can find the list of available modules here.

Self-built Modules

Here, we are going to code from scratch. We can build modules on our own and ship them. We can fine-tune them according to our use case. They are more customized, ideal, and mostly preferred for developers who like coding everything by themselves.

In the next sub-heading??, let’s discuss more on how to build module(s) from scratch by ourselves.


How to build your Python module

Playground Setup?

This blog lets us build a mini calculator program that runs on the CLI. Let’s implement it using modules to fulfill the objectives of the blog. You can create a new codedamn python playground online without requiring any local setup. It does support various languages as shown below:

Supported languages by the Codedamn Playground
Supported languages by the Codedamn Playground

For this blog, we will stick to Python. When you press Python you will be asked to provide a Playground Title. You are free to provide any name and hit the nice blue Create Playground button at the bottom.

Create a new Playground
Create a new Playground

After you click on Create Playground, wait for a few seconds to load the editor in your browser. Ultimately you will land on a page similar to this:

Codedamn Playground Python landing page
Codedamn Playground

If you arrived at this stage without hiccups, then you are good further, else reiterate the steps slowly. Now, let us move towards building the modules and see them in action.

Implementation⚙️

STEP-1: Create new files named main, add, sub, mul, and div with extensions as .py to store python code and refer to modules.

STEP-2: Each of the files does the work as the name specifies. They do addition, subtraction, multiplication, and division. All these functions are imported to the main script where the actual code lies required to execute.

STEP-3: Let’s look at the code which resides in each of the operations(+, -, *, /) files.

# add.py
def addition(a, b):
    print('Sum: ', a + b)
Code language: Python (python)
# sub.py
def difference(a, b):
    print('Difference: ', abs(a - b))
Code language: Python (python)
# mul.py
def multiplication(a, b):
    print('Product: ', a * b)
Code language: Python (python)
# div.py
def division(a, b):
    if (a >= b):
        print('Division: ', a / b)
    
    else:
        print('Division: ', b / a)
Code language: Python (python)

STEP-4: Then the next step is to import these individual python modules to the main.py file to implement the calculator functionality in CLI.

STEP-5: Here is the entire code for the main.py file:

# main.py

import add                              # Normal Import
from sub import difference              # Directly accessing the function
from mul import multiplication as m     # Using an alias
import div

def calculator(choice, num1, num2):
    if (choice == 1):
        return add.addition(num1, num2)

    elif (choice == 2):
        return difference(num1, num2)

    elif (choice == 3):
        return m(num1, num2)

    elif (choice == 4):
        return div.division(num1, num2)
    
    else:
        pass

print('*' * 40)
print('CALCULATOR-APP-CLI')
print('*' * 40)

while(True):
    print('Choose any one of the following operation to perform: ')
    print('1 - Addition')
    print('2 - Subtraction')
    print('3 - Multiplication')
    print('4 - Division')
    print('0 - Exit')

    print()

    try:
        choice = int(input('Enter choice of your wish: '))

    except ValueError:
        print()
        print('Please provide a integer between (0 - 4) as input⌨️')
        print()
        continue;

    if (choice == 0):
        print()
        print('Thanks for testing out?')
        print()
        break
    else:
        num1 = int(input('Enter number 1: '))
        num2 = int(input('Enter number 2: '))
        print('-' * 30)
        calculator(choice, num1, num2)
        print('-' * 30)

print('*' * 40)

Code language: Python (python)

Here are main focus lies on lines 3, 4, and 5 (as per the above snippet). Let us focus on each of the lines:

Line 3: A general import statement, which can be used to import any of the required block(s) of code, variables, etc from the target file. We simply use the dot(.) operator to import the necessary block of code.

Line 4: We use the from-import statement to import only a specific block of code or a variable. Here we have imported the difference function.

Line 5: An alias that instead of writing multiplication in all places we can simply use m to reduce the typing complexity. The alias name is provided by the user so you are free to use any.

The remaining chunks of code perform the job of making sure the working of calculator app in CLI.


Conclusion?

Here is the attached codedamn playground link for your reference. Feel free to fork, edit, and play with the code to understand more about modules better.

There is a comprehensive course Intermediate Python: Solidify your Python Understanding And Build Apps on codedamn. The best part about this course is that it is fully interactive. Tons of hands-on projects and exercises, lessons, articles, and quizzes to solidify your learnings.

Sharing is caring

Did you like what Sriniketh J wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far