Modules
Modules are Python files containing definitions and statements. They allow you to organize your code logically and reuse code across multiple projects.
# Creating a module (save as mymodule.py)
def greet(name):
print(f"Hello, {name}")
# Importing and using the module
import mymodule
mymodule.greet("Alice") # Hello, Alice
# Importing specific functions
from mymodule import greet
greet("Bob") # Hello, Bob
# Importing with an alias
import mymodule as mm
mm.greet("Charlie") # Hello, Charlie
Python comes with many built-in modules (like math, os, sys) that you can import and use in your programs.
Packages
Packages are a way of organizing related modules into a directory hierarchy. A package is essentially a directory containing Python modules and a special __init__.py file.
# Directory structure for a package
mypackage/
├── __init__.py # Required to make Python treat the directory as a package
├── module1.py
└── module2.py
# Importing from a package
import mypackage.module1
from mypackage import module2
# __init__.py can be empty or can contain initialization code
print("Initializing mypackage...")
from .module1 import some_function # Relative import
Packages allow for hierarchical structuring of module namespaces and help avoid naming conflicts between modules.
Python Standard Library
Python comes with a rich standard library that provides modules for many common programming tasks.
# Common standard library modules
import math # Mathematical functions
import os # Operating system interfaces
import sys # System-specific parameters
import datetime # Date and time handling
import json # JSON parsing and encoding
import re # Regular expressions
import random # Random number generation
# Example usage
print(math.sqrt(16)) # 4.0
print(datetime.date.today()) # Current date
print(random.choice(['a', 'b', 'c'])) # Random choice
The standard library is one of Python's greatest strengths, providing tools for many tasks right out of the box.
Third-Party Packages
Python has a vast ecosystem of third-party packages that can be installed using pip, Python's package installer.
# Installing packages with pip (run in terminal)
pip install numpy pandas matplotlib requests
# Using installed packages
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import requests
# Example: Create a numpy array
arr = np.array([1, 2, 3])
print(arr * 2) # [2 4 6]
# Example: Make an HTTP request
response = requests.get('https://api.github.com')
print(response.json())
Popular third-party packages extend Python's capabilities for data science, web development, machine learning, and more.
Virtual Environments
Virtual environments allow you to create isolated Python environments for different projects, preventing package conflicts.
# Creating a virtual environment (run in terminal)
python -m venv myenv
# Activating the environment
# On Windows:
myenv\Scripts\activate
# On macOS/Linux:
source myenv/bin/activate
# After activation, install packages normally
pip install flask
# Deactivating the environment
deactivate
# Listing installed packages
pip list
pip freeze > requirements.txt # Save to file
# Installing from requirements.txt
pip install -r requirements.txt
Virtual environments are essential for managing dependencies and ensuring project reproducibility.
Python Modules & Packages Videos
Master Python modules and packages with these handpicked YouTube tutorials:
Learn how to create and use Python modules:
Organizing code into packages:
Built-in modules you should know:
Managing dependencies and environments: