š Python Tutorial: Modules and Packages
As your Python programs grow in size and complexity, it's useful to organize your code into reusable files called modules, and directories of modules called packages. This helps keep code maintainable, reusable, and readable.
1. What is a Module?
A module is simply a Python file (.py) that contains functions, classes, or variables. You can import and use them in other files.
# greetings.py
def say_hello(name):
print(f"Hello, {name}!")# main.py
import greetings
greetings.say_hello("Alice")2. What is a Package?
A package is a directory that contains a special __init__.py file (can be empty) and one or more module files.
# directory structure:
my_package/
āāā __init__.py
āāā math_utils.py
āāā string_utils.pyYou can import functions from modules inside a package:
from my_package.math_utils import add
result = add(2, 3)3. Built-in Modules
Python comes with many useful standard modules like math, random, datetime, and more.
import math
print(math.sqrt(16)) # 4.04. Installing Third-Party Packages
Use pip to install external packages:
pip install requestsThen import and use them in your script:
import requests
response = requests.get("https://api.github.com")
print(response.status_code)