Skip to content

Module 19 · Debugging, Testing and Best Practices — topic 12 of 15

Naming conventions

Applying Python's naming conventions in real code: snake_case, PascalCase and UPPER_CASE, leading underscores, choosing descriptive names, boolean and function naming patterns, and checking names automatically.

Beginner 8 min read·Lesson 290 of 306 in Python Programming

Learning objectives

  • Apply Python's naming styles consistently
  • Choose descriptive names for variables, functions and booleans
  • Detect names that break conventions

Definition

Naming conventions are agreed rules for how identifiers are written. In Python: snake_case for variables, functions and modules; PascalCase for classes; UPPER_CASE for constants; a leading underscore for internal names.

Introduction

Just by reading MAX_RETRIES, OrderService and place_order, a Python programmer knows which is a constant, a class and a function. Conventions carry meaning.

Why it matters

Good names are the cheapest documentation. Consistent styles let readers understand code structure at a glance.

Detailed explanation

Variables, functions, methods and modules: snake_case (total_price, load_users, data_loader.py).

Classes and exceptions: PascalCase (ShoppingCart, InvalidOrderError).

Constants: UPPER_CASE (TAX_RATE, MAX_RETRIES), usually defined at module level.

A single leading underscore marks internal names (_cache); a trailing underscore avoids clashes with keywords (class_).

Functions do things, so name them with verbs: calculate_total, send_email. Booleans read as yes/no questions: is_valid, has_items, can_edit.

Prefer full words to abbreviations (customer_count, not cust_cnt); short names like i or x are fine only for tiny scopes such as loop indexes.

Avoid shadowing built-ins: don't name variables list, dict, str, sum or id.

Rename freely while code is young; editors' rename tools update every use safely.

Use the vocabulary of the problem domain: if users talk about invoices and customers, the code should have Invoice and customer_id rather than Record and person_num. Shared words make conversations about the code much easier.

Plural names suggest collections (students, prices) and singular names single items (student, price), which makes loops like for student in students read naturally.

Syntax

Python
MAX_RETRIES = 3 # constant
class OrderService: # class
def place_order(self, item): # method (verb)
is_valid = bool(item) # boolean
self._attempts = 0 # internal
  • snake_case, PascalCase, UPPER_CASE.
  • Verbs for functions, questions for booleans.
  • Don't shadow built-ins.

Code examples

Vague versus descriptive

Python
def calc(a, b):
return a * b / 100
def percentage_of(total, percent):
return total * percent / 100
print(calc(250, 12), percentage_of(250, 12))
Output
30.0 30.0

Conventions together

Python
MAX_RETRIES = 3
class OrderService:
def __init__(self):
self._attempts = 0
def place_order(self, item):
self._attempts += 1
return f"order for {item} (attempt {self._attempts} of {MAX_RETRIES})"
print(OrderService().place_order("book"))
Output
order for book (attempt 1 of 3)

More examples

Checking names automatically

Python
import re
names = {
"function": ["get_user", "GetUser", "calc_total2"],
"class": ["UserProfile", "user_profile"],
"constant": ["MAX_SIZE", "MaxSize"],
}
rules = {"function": r"[a-z_][a-z0-9_]*", "class": r"[A-Z][A-Za-z0-9]*", "constant": r"[A-Z][A-Z0-9_]*"}
for kind, items in names.items():
for name in items:
verdict = "ok" if re.fullmatch(rules[kind], name) else "rename"
print(f"{kind:<9}{name:<13}{verdict}")
Output
function get_user     ok
function GetUser      rename
function calc_total2  ok
class    UserProfile  ok
class    user_profile rename
constant MAX_SIZE     ok
constant MaxSize      rename

Step-by-step explanation

  • Each kind of identifier has a regular expression describing its convention.
  • fullmatch requires the whole name to fit the pattern.
  • Linters such as ruff (with the pep8-naming rules) perform the same checks on real code.

Expected output

Running “Checking names automatically” prints exactly:

TextOutput
function get_user ok
function GetUser rename
function calc_total2 ok
class UserProfile ok
class user_profile rename
constant MAX_SIZE ok
constant MaxSize rename

Practical applications

  • Team style guides and code review comments.
  • APIs whose names make documentation almost unnecessary.

Best practices

  • Follow PEP 8 naming styles.
  • Use verbs for functions and questions for booleans.
  • Prefer clarity over brevity.

Common mistakes

Shadowing a built-in

Avoid

list = [1, 2, 3]
list("abc") # TypeError

Prefer

numbers = [1, 2, 3]

The built-in list is hidden by your variable.

Important notes

  • Names in other languages' conventions (camelCase) are common in code ported to Python; convert them when you can.

Key takeaways

  • snake_case for functions and variables, PascalCase for classes, UPPER_CASE for constants.
  • Leading underscore means internal.
  • Descriptive names beat abbreviations.

Try it yourself

  1. 1
    Rename the variables in a short script to be descriptive and PEP 8 compliant.
  2. 2
    Extend the name checker to flag names that shadow built-ins.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

10 questions cover the “Debugging, Testing and Best Practices” module. Answers and explanations are revealed after you submit.

  • AdvancedWhy shouldn't assert be used to validate user input?
  • AdvancedWhat is printed?
  • AdvancedWhere should you usually start reading a Python traceback?
Practise this module