Packages in Python
In Python, as programs grow larger, organizing modules becomes important. A package is a way to organize related modules together in a folder so that they can be used efficiently.
What is a Package?
A package is a collection of Python modules grouped together inside a folder.
- Each package contains a special file called
__init__.py(can be empty) - Packages help in structuring large programs and avoiding naming conflicts
In short:
- Module → single Python file
- Package → folder containing multiple modules
1. Using a Built-in Package
Python comes with built-in packages like os,
sys, and math.
Example
import os
print(os.name)
print(os.getcwd())
Explanation
osis a built-in package for interacting with the operating system.os.nametells the type of operating system.os.getcwd()returns the current working directory.- Using the package avoids writing OS-related functions manually.
2. Creating a User-Defined Package
You can create your own package by organizing modules in a folder.
Step 1: Create folder mypackage
Inside it, create two modules:
module1.py
def greet():
print("Hello from module1")
module2.py
def welcome():
print("Welcome from module2")
Step 2: Create __init__.py (can be empty)
Step 3: Use the package
from mypackage import module1, module2
module1.greet()
module2.welcome()
Explanation
mypackageis a folder containing multiple modules.__init__.pymakes Python treat the folder as a package.- Functions from different modules are accessed using import.
Output
Hello from module1
Welcome from module2
3. Advantages of Using Packages
- Organized Code – Keeps related modules together
- Reusability – Modules can be reused across programs
- Avoid Name Conflicts – Same module names can exist in different packages
Example
mypackage/
__init__.py
module1.py
module2.py
utilities/
__init__.py
helper1.py
helper2.py
Access via:
from mypackage import module1
Makes code easier to maintain and understand.