Modules and Packages in Python
Modules and packages in Python are used to organize code and reuse functionality across programs.
Modules:
A module is a Python file containing functions, variables, and classes that can be imported into other programs.
Creating a module:
Create a Python file, e.g., mymodule.py:
def greet(name):
print("Hello", name)
Importing a module:
import module_name
Example:
import mymodule
mymodule.greet("Alice")
Import specific function or variable:
from mymodule import greet
greet("Bob")
Import with alias:
import mymodule as mm
mm.greet("Charlie")
Built-in modules:
Python provides many built-in modules such as math, random, os, sys, datetime.
Example:
import math
print(math.sqrt(16)) # 4.0
dir() function:
Lists all functions and variables in a module.
Example:
import math
print(dir(math))
Packages:
A package is a collection of modules organized in a folder with an __init__.py file.
It allows hierarchical structuring of modules.
Creating a package:
Folder structure:
mypackage/
init.py
module1.py
module2.py
Importing from a package:
from mypackage import module1
module1.some_function()
Importing specific items from a package:
from mypackage.module1 import some_function
some_function()
Installing external packages:
Use pip to install packages from PyPI.
Example:
pip install requests
import requests
Common built-in package examples:
os → file and directory operations
sys → system-specific parameters
random → generate random numbers
datetime → date and time functions
math → mathematical functions
Benefits of modules and packages:
Reuse code
Better organization
Avoid name conflicts
Easier maintenance
Take quizzes related to this topic and see where you stand!
Start Quiz Now