Python Module

Any text file with .py extension and containing Python code is basically a module. Different Python objects such as functions, classes, variables, constants etc. defined in one module can be made available to interpreter session or another Python script by using import statement. Functions defined in built-in modules need to be imported before use. On similar lines, a custom module may have one or more user defined Python objects in it. These objects can be imported in interpreter session or another script.

  If the programming algorithm requires defining a lot of functions and classes, they are logically organised in modules. One module stores classes, functions and other resources of similar relevance. Such a modular structure of the code makes it easy to understand, use and maintain.


Creating a Module in Python

Shown below is a Python script containing definition of SayHello() function. It is saved as hello.py

def SayHello(name):
    print("Hello {}! How are you?".format(name))
    return

Importing module

We can now import this module and execute SayHello() function from Python prompt.


import hello 
 hello.SayHello("durgesh") 
Hello durgesh! How are you?

In the same way, to use the above hello module in another Python script, use import statement.

Renaming the Imported Module

Use as keyword to rename the imported module as shown below.


import math as cal
cal.log(4)
1.3862943611198906
woman avatar

What we are going to learn in Python Modules