Modules and packages help organize Python code into reusable, maintainable, and logical units.
1) What is a Module?
A module is a single Python file (.py) that contains Python code — functions, classes, or variables — that can be imported and reused in other Python programs.
# example_module.py
def greet(name):
return f"Hello, {name}!"
pi = 3.14159
2) How to Use a Module
You can import modules using the import statement:
# main.py
import example_module
print(example_module.greet("Alice"))
print(example_module.pi)
Other ways to import:
# Import specific items
from example_module import greet, pi
# Import with alias
import example_module as em
print(em.greet("Bob"))
3) What is a Package?
A package is a collection of Python modules organized in directories with a special file __init__.py.
Packages allow better organization of large projects.
project/
│
├── package_name/
│ ├── __init__.py
│ ├── module1.py
│ └── module2.py
└── main.py
4) How to Use a Package
# Import a module from a package
from package_name import module1
module1.some_function()
# Import specific item
from package_name.module2 import some_class
obj = some_class()
Packages can also have nested packages, making it easy to organize large projects.
5) Common Built-in Modules
Python comes with a rich standard library of modules:
math– Mathematical operationsos– Interact with the operating systemsys– Python runtime environmentrandom– Random numbers and selectionsdatetime– Date and time operationsjson– Working with JSON data
import math
print(math.sqrt(16)) # 4.0
import random
print(random.choice([1, 2, 3, 4])) # random element
6) Differences Between Modules and Packages
| Aspect | Module | Package |
|---|---|---|
| Definition | Single Python file (.py) |
Directory of modules containing __init__.py |
| Purpose | Organize reusable code in one file | Organize multiple modules and subpackages |
| Example | math.py |
numpy/ (contains multiple modules) |
7) Common Mistakes
- Importing modules/packages that don’t exist →
ModuleNotFoundError - Using relative imports incorrectly in packages
- Using the same name as a built-in module (e.g., naming your file
math.py) → conflicts - Forgetting
__init__.pyin older Python versions (needed for package recognition)
No comments:
Post a Comment