Skip to main content

Python Naming Best Practices

Python follows the PEP 8 style guide for naming conventions. This guide helps improve code readability and maintainability across files, classes, methods, and variables. Below are best practices for naming in Python:

1. File Names

  • Should be lowercase.
  • Use underscores (_) to separate words for readability.
  • Example:
    user_controller.py
    data_processor.py

2. Class Names

  • Should use the CapWords (also called CamelCase or PascalCase) convention.
  • Each word starts with a capital letter, no underscores.
  • Example:
    class DataProcessor:
    pass

    class UserController:
    pass

3. Method and Function Names

  • Should be lowercase, with words separated by underscores (_) for readability.
  • Example:
    def process_data(self):
    pass

    def get_user_info(user_id):
    pass

4. Variable Names

  • Should be lowercase, with underscores (_) to improve readability.
  • Example:
    total_count = 0
    user_name = "Alice"

5. Constants

  • Use all uppercase letters, with words separated by underscores (_).
  • Example:
    MAX_ATTEMPTS = 3
    API_KEY = "your-api-key"

6. Private Members

  • Prefix with a single underscore (_), by convention, to indicate that it is for internal use.
  • Example:
    class Example:
    def _internal_method(self):
    pass

    def public_method(self):
    pass

7. Special Methods

  • Python’s special methods (aka "magic methods") use double underscores before and after the name (e.g., __init__, __str__). These are reserved for Python's internal use.

Summary Table

ContextConventionExample
Filesnake_casemy_script.py
ClassCapWordsMyClass
Function/Methodsnake_casemy_function()
Variablesnake_casemy_variable
ConstantUPPER_CASEMY_CONSTANT
Private Member_snake_case (prefix)_my_private_member

Following these conventions keeps your Python code professional, clean, and easy to understand for others and for yourself in the future.