Python Modules

A module in Python contains Python definitions and statements. Python modules are similar to a code library. In this blog, we will explore Python modules in details.

What is Python Module?


A Python module is a set of code which may include functions, classes and variables. Python module is a code which can be imported in some other source code to provide code re-usability.

In general, a module is a file contains Python code.

How to Create a Python Module?

To understand Modules in Python, first create a file with name Module1.py and write below code -

def Function1(a, b):
    print(a+b)


Import Module in Python


Once the module is ready, we will use this module in separate source code by using import statement.
When interpreter found an import statement in Python source code, it import the module and made available for current source code if found in specified location.

Now create a new file with name TestModule.py and write below code -

import Module1
Module1.Function1(10,20)

Execute the TestModule.py file by using below command -

python TestModule.py

And you will see that code written in Module1.py gets executed.

Variables in Modules

As mentioned above that, a Python module can contains functions and variables as well.

Product = {
     "ProductId":1,
     "Name":"Product1",
     "Category":"Electronics",
     "Cost":15000.00
 }


Above Code can be used as Module using Import statement -

import Module1
Product = Module1.Product["Name"]
Cost = Module1.Product["Cost"]
print(Product)
print(Cost)

There are readymade Modules available in Python. Some of the Modules are -
pyodbc, math etc
In Python, you can create an alias for your module. Create an alias for Module1 and call functions or property with the alias name.
import Module1 as m
m.Function1(10,20)
  



Previous Blog - How to Connect Python with SQL Server using Pyodbc?

Hope you like this blog.

Comments