Packages in Python
A package is a collection of related modules organized inside directories. Packages help manage large Python projects efficiently.
💡 A package is simply a folder that contains Python modules.
Package Structure
A package must contain a special file called __init__.py.
mypackage/
│
├── __init__.py
├── math_utils.py
└── string_utils.py
Creating a Package
Create a folder and add Python files inside it.
# math_utils.py
def add(a, b):
return a + b
Using a Package
Import modules from a package like this:
from mypackage import math_utils
print(math_utils.add(5, 7))
Import Specific Functions
from mypackage.math_utils import add
print(add(10, 20))
Built-in Python Packages
Python provides many useful built-in packages such as:
- os – interacting with the operating system
- sys – system-specific parameters
- collections – advanced data structures
- json – working with JSON data
Practice Exercises
- Create a package with two modules
- Import a function from one module
- Use a built-in package like
os