Modules and packages help in organizing Python code by grouping related functions, classes, or variables.
- Module: A file containing Python definitions and statements (i.e., a
.py
file). - Package: A directory containing a collection of modules and a special
__init__.py
file.
Importing Modules:
import math
print(math.pi) # Output: 3.141592653589793
print(math.sqrt(16)) # Output: 4.0
Importing Specific Functions:
from math import sqrt, pow
print(sqrt(25)) # Output: 5.0
print(pow(2, 3)) # Output: 8.0
Creating a Module:
Create a file named mymodule.py
:
# mymodule.py
def greet(name):
print(f"Hello, {name}!")
Use it in another script:
import mymodule
mymodule.greet("Alice") # Output: Hello, Alice!
Packages:
Directory structure:
mypackage/
__init__.py
module1.py
module2.py
Importing from a package:
from mypackage import module1
module1.function()