Python Naming Conventions (PEP 8): The Definitive Reference

6 min read

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

PatternConventionExample
Private attribute_single_leading_underscore_internal_cache
Name mangling__double_leading_underscore__private_method
Magic / dunder__double_both____init__, __str__
Throwaway variableSingle underscorefor _ in range(10)
Type variablePascalCase, shortT, KT, VT

Common Mistakes

  • Using camelCase for functions (getUserName instead of get_user_name)
  • Using lowercase for class names (user_account instead of UserAccount)
  • 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.