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 and write below code –

def Function1(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 and write below code –

import Module1

Execute the file by using below command –


And you will see that code written in gets executed.

Variables in Modules

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

Product = {

Above Code can be used as Module using Import statement –

import Module1
Product = Module1.Product["Name"]
Cost = Module1.Product["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

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

Hope you like this blog.

Leave a Comment