PEP 8 and Code Style
PEP 8 is the official Python style guide. Following PEP 8 makes your code consistent and readable, which is especially important when working in teams. Most Python projects and companies expect PEP 8 compliance.
Linters like flake8 and formatters like black can automatically check and fix your code style.
Example
# PEP 8 Examples
# Good: snake_case for variables and functions
user_name = "Alice"
def calculate_total(price, tax_rate):
return price * (1 + tax_rate)
# Good: PascalCase for classes
class ShoppingCart:
pass
# Good: UPPER_CASE for constants
MAX_RETRIES = 3
BASE_URL = "https://api.example.com"
# Good: 4-space indentation
def process_items(items):
for item in items:
if item.is_valid():
item.process()
# Good: spaces around operators
x = 10 + 5
y = x * 2
# Good: descriptive names
def calculate_average(scores):
"""Calculate the average of a list of scores."""
if not scores:
return 0
return sum(scores) / len(scores)
# Bad examples to avoid:
# x=10+5 (missing spaces)
# def f(l): (non-descriptive names)
# calculateAverage() (camelCase for function)
# class shopping_cart: (snake_case for class) - Use snake_case for functions, methods, and variables
- Use PascalCase for class names
- Use UPPER_SNAKE_CASE for constants
- Use 4 spaces for indentation (never tabs)
- Limit lines to 79 characters (or 99 in modern projects)
- Add two blank lines before top-level function/class definitions
- Add one blank line between methods inside a class
- Write docstrings for all public modules, functions, classes, and methods
Try Clean Code Style
JavaScript
# Following PEP 8 conventions
MAX_STUDENTS = 30
def calculate_average(scores):
"""Calculate the average of a list of scores."""
if not scores:
return 0.0
return sum(scores) / len(scores)
class Student:
def __init__(self, name, grades):
self.name = name
self.grades = grades
def get_average(self):
return calculate_average(self.grades)
student = Student("Alice", [90, 85, 92, 88])
print(f"{student.name}: {student.get_average():.1f}") Notes
- Install flake8 (pip install flake8) and run it on your files to catch style issues. Or use black (pip install black) to auto-format your code.
Virtual Environments and Project Organization
Virtual environments isolate your project's dependencies from the system Python and from other projects. This prevents version conflicts and makes your project reproducible.
A well-organized Python project follows a standard directory structure and uses requirements.txt or pyproject.toml to track dependencies.
Example
# Creating and using a virtual environment
# In terminal:
# Create a virtual environment
# python -m venv myproject_env
# Activate it
# Windows: myproject_env\Scripts\activate
# macOS/Linux: source myproject_env/bin/activate
# Install packages (only affects this environment)
# pip install requests flask
# Save dependencies
# pip freeze > requirements.txt
# Install from requirements (on another machine)
# pip install -r requirements.txt
# Deactivate when done
# deactivate
# Recommended project structure:
# my_project/
# ├── README.md
# ├── requirements.txt
# ├── .gitignore
# ├── src/
# │ ├── __init__.py
# │ ├── main.py
# │ ├── models.py
# │ └── utils.py
# ├── tests/
# │ ├── __init__.py
# │ ├── test_main.py
# │ └── test_utils.py
# └── docs/
# └── usage.md
# .gitignore for Python projects
# __pycache__/
# *.pyc
# myproject_env/
# .env
# *.egg-info/ - Always use virtual environments for every project
- Keep requirements.txt updated with pip freeze > requirements.txt
- Add your virtual environment folder to .gitignore
- Use __init__.py files to make directories into packages
- Separate source code, tests, and documentation into different folders
- Write docstrings and comments for complex logic
- Use type hints for function signatures in larger projects
Try Type Hints
JavaScript
# Type hints improve code readability
def calculate_bmi(weight: float, height: float) -> float:
"""Calculate BMI given weight (kg) and height (m)."""
return weight / (height ** 2)
def greet_users(names: list[str]) -> None:
for name in names:
print(f"Hello, {name}!")
bmi = calculate_bmi(70, 1.75)
print(f"BMI: {bmi:.1f}")
greet_users(["Alice", "Bob", "Charlie"]) Notes
- Type hints in Python are optional and not enforced at runtime. They serve as documentation and can be checked with tools like mypy.
