Skip to content

Python naming conventions Cheat Sheet

  • by

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.

Python naming conventions Cheat Sheet

Let’s see the cheat sheet for Python naming conventions:

Naming ElementConventionExample
Module Nameslowercase with underscoresmy_module.py
Package Nameslowercase with underscoresmy_package
Class NamesCamelCase without underscoresMyClass
Function Nameslowercase with underscoresmy_function
Variable Nameslowercase with underscoresmy_variable
Constant Namesuppercase with underscoresMY_CONSTANT
Private Namesleading underscore_private_method, _private_variable
Type Variable Namessingle uppercase letterT, U
Module-Level Constantsuppercase with underscoresMY_CONSTANT
Single Underscoregenerally avoid unless with a purpose_ (as a throwaway variable)
Double Underscoresavoid at the beginning or end of a nameNot applicable
Avoid Generic Namesavoid generic or common namesdata, 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.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading