Modules & Packages
Module
A module is a single Python file containing reusable code (functions, classes, variables)- File with .py extension
- Can be imported using import module_name
- Provides code reusability and organization
We created the module with the name of operations.py
def add(a, b):
a+b
def subtract (a, b):
a-b
We are going to use functions in operations.py file via import.
import operations as op
addition = op.add(3,4)
print(addition)
Package
A package is a collection of modules organized in directories with a special __init__.py file.- Directory containing Python files
- Must contain __init__.py (can be empty)
- Can have sub-packages (nested directories)
Example:
my_package/
│ __init__.py
│ module1.py
│ module2.py
└───subpackage/
│ __init__.py
│ module3.py
Import Type | Syntax | Description |
---|---|---|
Module Import | import module |
Imports entire module (access with module.function() ) |
Specific Import | from module import function |
Imports specific function/class directly |
Package Import | import package.module |
Imports module from a package |
Alias Import | import module as md |
Imports with an alias name |