Python Module

Module in Python is basically a file that contains some set of functions and/or objects. For example:

def greet():
    print("Hey,")
    print("a warm welcome from my side.")

Save this code in a file with extension .py say mod.py. Put this file in the current directory, the directory where the Python program (source code) is available. Here is the snapshot of the current directory, in my case:

python module

Note - The source code of codescracker.py file is given below.

Now create a program, that imports the above newly created module named mod.py to use function defined inside that module, in the program. For example:

import mod

mod.greet()

This will produce following output:

Hey,
a warm welcome from my side.

Note - The import statement/keyword is used to load a module in Python.

Important - The module file must saved with .py extension

Why we Need to Create a Module in Python ?

If you're creating an application in Python, that has extensive number of functions, variables and/or other objects, then better to put some or all those functions, variables, and/or other objects inside a separate file called module.

It becomes easy to re-define or edit the module file, that contains some part of the actual program, without opening the source code file. Also the source code file will get smaller, and becomes easy to handle.

Note - Modules some time helps to organize the code. Also the large program becomes short, after grouping the related codes into module(s).

How to Use a Module in Python ?

To use a module, in Python, first load the module, using the import keyword. Here is the syntax:

import module_name

If you want to load only particular function of a module, then use import along with from keyword in this way:

from module_name import function_name

After loading the module in program, use functions defined in that module, in this way:

module_name.function_name

Note - While using a function defined in a module, it is required to bound the function with the module. Since sometime in large application, there may be multiple functions with same name defined in different modules. And if those modules are loaded inside the same program, then directly calling the function, will raise error.

Python Module Example - Create and Use a Module in Program

As already said, module is a file, ending with .py extension, containing some block of codes. For example, save the following block of codes in a file say mymodule.py:

def sum(a, b):
    return a+b

def sqr(x):
    return x*x

def cub(x):
    return x*x*x

def msg():
    print("Enter the Number: ", end="")

And to use this module, create another program. For example:

import mymodule

choice = 1
while 1 <= choice <= 4:
    print("\n1. Sum")
    print("2. Square")
    print("3. Cube")
    print("4. Exit")
    print("Enter Your Choice (1-4): ", end="")
    choice = int(input())

    if choice == 1:
        mymodule.msg()
        numOne = int(input())
        mymodule.msg()
        numTwo = int(input())
        res = mymodule.sum(numOne, numTwo)
        print("\nResult =", res)

    elif choice == 2:
        mymodule.msg()
        num = int(input())
        res = mymodule.sqr(num)
        print("\nResult =", res)

    elif choice == 3:
        mymodule.msg()
        num = int(input())
        res = mymodule.cub(num)
        print("\nResult =", res)

    elif choice == 4:
        choice = 5

    else:
        choice = 1
        print("\nInvalid Choice!")

The sample run with some user inputs, is shown in the snapshot given below:

python create module with example

Using Built-in Module in Python

Some built-in modules are also defined by Python's creator. For example:

import operator

print(operator.add(10, 30))

The output is:

40

Here the operator module is a built-in module, pre-defined by Python's creator.

Create and Use Variables/Objects from Module in Python

Including functions, we can also define lists, dictionaries, and some other objects in a module. For example, the following code is in a module named mod.py:

mylist = [12, 32, 43, 53]
mydict = {"Name": "Louis", "Course": "EECS"}

Now we can use the above list and dictionary defined in mod.py module. For example:

import mod

print(mod.mylist[0])
print(mod.mylist[1])

print(mod.mydict["Name"])
print(mod.mydict["Course"])

The output is:

12
32
Louis
EECS

Re-name a Module in a Program in Python

The as keyword is used when we need to define a duplicate name to a module in a program. For example:

import mod as m

print(m.mylist[0])
print(m.mydict["Name"])

The output is:

12
Louis

In above program, the following statement:

import mod as m

loads the module named mod, and defines a duplicate name m to it. Now, we need to write m in place of mod to access any objects/functions defined in the module mod.

Python Online Test


« Previous Tutorial Next Tutorial »

Follow/Like Us on Facebook




Subscribe Us on YouTube