Python Naming Conventions: A Comprehensive Cheat Sheet
Python's readability and simplicity are among its most appealing features. Adhering to Python's naming conventions is crucial for maintaining this readability and ensuring your code is easy to understand and maintain. Here's a cheat sheet to help you master Python's naming conventions.
Naming Variables and Functions
In Python, variable and function names are case-sensitive and can contain letters (a-z, A-Z), digits (0-9), or underscores (_). They cannot start with a digit. Here are some guidelines:
- Lowercase with words separated by underscores (snake_case): This is the most common convention in Python. Words are separated by underscores, making it easy to read. For example: `my_variable`, `my_function`
- Lowercase with words separated by no spaces (camelCase): While not as common, this convention is sometimes used for function and variable names. Words are not separated by spaces or underscores. For example: `myVariable`, `myFunction`
Naming Constants
Constants are variables whose values do not change. In Python, constants are named in all uppercase letters with words separated by underscores. For example: `MY_CONSTANT = 10`

Naming Classes
Class names should be in the CapWords convention, where each word is capitalized and there are no spaces or underscores. For example: `MyClass`, `MyLongerClassName`
Naming Methods
Method names should be lowercase, with words separated by underscores, following the same convention as variable names. For example: `my_method`, `my_longer_method`
Naming Modules and Packages
Module and package names should be all lowercase, with words separated by underscores. For example: `my_module`, `my_package`

Naming Private Variables and Methods
Python uses name mangling to indicate private variables and methods. To create a private variable or method, prefix the name with an underscore. For example: `_my_private_variable`, `_my_private_method`
Naming Conventions for File Names
File names should be all lowercase, with words separated by underscores. The file extension should be `.py`. For example: `my_file.py`, `my_longer_file_name.py`
Table: Python Naming Conventions Summary
| Type | Naming Convention | Example |
|---|---|---|
| Variable/Function | snake_case | my_variable, my_function |
| Constant | ALL_CAPS | MY_CONSTANT |
| Class | CapWords | MyClass |
| Method | snake_case | my_method |
| Module/Package | snake_case | my_module, my_package |
| Private Variable/Method | snake_case with prefix underscore | _my_private_variable, _my_private_method |
| File Name | snake_case | my_file.py |
Adhering to these naming conventions will make your Python code more readable and maintainable. It's a small investment that pays off in the long run. Happy coding!























