Python Naming Conventions (PEP 8): The Definitive Reference
PEP 8 is Python's official style guide, and its naming conventions are followed by virtually every Python project. This guide covers every rule you need to know.
Why PEP 8 Matters
Python emphasizes readability. PEP 8 ensures that code written by different developers looks and feels the same. Linters like flake8, pylint, and ruff enforce these conventions automatically.
Variable and Function Names: snake_case
All variables and functions use lowercase with underscores:
user_name = "Alice"
total_price = 99.95
def get_user_by_id(user_id):
pass
def calculate_total_price(items):
pass
Never use camelCase for Python functions. Writing getUserById is immediately recognizable as non-Pythonic.
Class Names: PascalCase
Classes use CapWords (PascalCase):
class UserAccount:
pass
class HttpRequestHandler:
pass
Constants: SCREAMING_SNAKE_CASE
Module-level constants use all uppercase with underscores:
MAX_RETRY_COUNT = 3
API_BASE_URL = "https://api.example.com"
DEFAULT_TIMEOUT = 30
Module and Package Names
Modules (files) should be short, all lowercase, with underscores if needed: utils.py, data_loader.py. Packages (directories) should be short, all lowercase, without underscores: mypackage.
Method Names and Instance Variables
Same as functions — snake_case. Use a single leading underscore for internal (non-public) methods:
class User:
def __init__(self, name):
self.user_name = name
self._internal_id = generate_id()
def get_display_name(self):
return self.user_name
def _validate(self):
pass
Special Cases
| Pattern | Convention | Example |
|---|---|---|
| Private attribute | _single_leading_underscore | _internal_cache |
| Name mangling | __double_leading_underscore | __private_method |
| Magic / dunder | __double_both__ | __init__, __str__ |
| Throwaway variable | Single underscore | for _ in range(10) |
| Type variable | PascalCase, short | T, KT, VT |
Common Mistakes
- Using camelCase for functions (
getUserNameinstead ofget_user_name) - Using lowercase for class names (
user_accountinstead ofUserAccount) - Using ALL_CAPS for regular variables
- Single-letter variable names outside of loops or comprehensions
Quick-Convert Your Code
If you're migrating from JavaScript or Java, use our snake_case converter to quickly transform camelCase identifiers. For class names, try the PascalCase converter. The case converter hub lets you compare all formats at once.
Summary
PEP 8 naming is simple: snake_case for almost everything, PascalCase for classes, SCREAMING_SNAKE for constants. Follow these rules and your Python code will feel natural to every Python developer.