Python naming conventions cheat sheet provides a concise reference guide for naming conventions in Python programming. It typically includes the recommended conventions for naming modules, packages, classes, functions, variables, constants, private names, type variables, and more.
Let’s see the cheat sheet for Python naming conventions:
Naming Element | Convention | Example |
---|---|---|
Module Names | lowercase with underscores | my_module.py |
Package Names | lowercase with underscores | my_package |
Class Names | CamelCase without underscores | MyClass |
Function Names | lowercase with underscores | my_function |
Variable Names | lowercase with underscores | my_variable |
Constant Names | uppercase with underscores | MY_CONSTANT |
Private Names | leading underscore | _private_method , _private_variable |
Type Variable Names | single uppercase letter | T , U |
Module-Level Constants | uppercase with underscores | MY_CONSTANT |
Single Underscore | generally avoid unless with a purpose | _ (as a throwaway variable) |
Double Underscores | avoid at the beginning or end of a name | Not applicable |
Avoid Generic Names | avoid generic or common names | data , value |
Python naming conventions Cheat Sheet Example
Simple example code.
# Module Names
my_module.py
# Package Names
my_package
# Class Names
class MyClass:
pass
# Function and Variable Names
def my_function():
my_variable = 10
# Constant Names
MY_CONSTANT = 100
# Private Names
class MyClass:
def __init__(self):
self._private_variable = 5
def _private_method(self):
pass
# Type Variable Names
T = TypeVar('T')
# Module-Level Constants
MY_MODULE_CONSTANT = 42
# Single Underscore (Throwaway Variable)
for _ in range(5):
print("Hello")
# Avoid Generic Names
data = "example" # Less preferred
student_name = "John" # More descriptive
These examples showcase the naming conventions discussed earlier. Remember to apply these conventions consistently in your Python code to improve readability and maintainability.
Comment if you have any doubts or suggestions on this Python naming convention topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.