Modules and Packages in Python

 In Python, a module is a file containing Python code such as functions, variables, and classes.

A package is a collection of modules organized in directories.

Modules and packages help to:

  • Organize large programs

  • Reuse code

  • Avoid rewriting code

  • Improve maintainability

Module in Python

A module is simply a Python file with .py extension.

Example:
File name: mymodule.py

def greet(name):
return "Hello " + name

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

Now we can use this module in another file.

Importing a Module

To use a module, we use the import keyword.

Import Entire Module

import mymodule

print(mymodule.greet("Arun"))
print(mymodule.add(10, 5))

Import Specific Function

from mymodule import greet

print(greet("Kumar"))

Import with Alias

import mymodule as mm

print(mm.add(5, 3))

Alias makes the module name shorter.

Built-in Modules

Python provides many built-in modules.

Some commonly used modules:

  • math

  • random

  • datetime

  • os

  • sys

Example using math module:

import math

print(math.sqrt(25))
print(math.pi)

Example using random module:

import random

print(random.randint(1, 10))

The dir() Function

dir() is used to list all functions and variables inside a module.

Example:

import math
print(dir(math))

Creating Your Own Module

Steps:

  1. Create a Python file (example: calculator.py)

  2. Write functions inside it

  3. Save the file

  4. Import it in another Python file

Example:

calculator.py

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

def subtract(a, b):
return a - b

Main file:

import calculator

print(calculator.add(10, 3))

 Package in Python

A package is a directory (folder) that contains multiple modules.

A package must contain a special file called:

__init__.py

This file tells Python that the folder is a package.

Structure of a Package

Example folder structure:

mypackage/
__init__.py
module1.py
module2.py

Using a Package

Suppose module1.py contains:

def message():
return "Welcome to Package"

Now in main file:

from mypackage import module1

print(module1.message())

Importing Specific Function from Package

from mypackage.module1 import message

print(message())

Difference Between Module and Package

ModulePackage
Single Python fileFolder containing multiple modules
Contains functions and variables        Contains multiple modules
Example: math.pyExample: mypackage

Advantages of Modules and Packages

✔ Code Reusability
✔ Better Organization
✔ Easy Maintenance
✔ Avoid Name Conflicts
✔ Suitable for Large Projects

Conclusion

Modules and packages are very important in Python programming.

They help in organizing code into smaller parts, making programs easier to understand and maintain.

In large applications, packages are used to structure the project properly.

Comments

Popular posts from this blog

Functions in Python

Tkinter -Python

Python – Database Connection