Naming
14 min
Good names are the cheapest, highest-leverage form of documentation —
def calc(d, n) tells you nothing; def calculate_average(daily_sales, num_days) tells you almost everything without a single comment.
Python's own convention (PEP 8) for variables and functions is
snake_case: lowercase words separated by underscores.
import re
def is_snake_case(name):
return bool(re.match(r"^[a-z_][a-z0-9_]*$", name))
print(is_snake_case("user_name")) # True
print(is_snake_case("userName")) # False -- camelCase, not Python's convention
Same logic, same number of lines of actual computation -- but the second version needs zero comments to understand, because the names ALREADY explain what's happening. That's the entire goal of naming well.
Boolean names deserve special care — a name like active is ambiguous
(is it a question? a command? a state?), while is_active reads
naturally wherever booleans get used, especially in conditionals:
def is_boolean_name_clear(name):
return name.startswith(("is_", "has_", "can_", "should_"))
print(is_boolean_name_clear("is_valid")) # True
print(is_boolean_name_clear("valid")) # False -- ambiguous on its own
if is_valid: reads like an English sentence. if valid: is fine too,
honestly — but is_/has_/can_/should_ prefixes remove any
ambiguity about whether a name is a boolean at all, which matters more
the bigger and less-familiar a codebase gets.
Write `is_snake_case(name)`: return True if `name` matches Python's `snake_case` convention — lowercase letters, digits, and underscores only, not starting with a digit.
Write `is_boolean_name_clear(name)`: return True if `name` starts with a conventional boolean prefix — `is_`, `has_`, `can_`, or `should_`.
Why is `is_active` a better boolean variable name than `active` or `flag`?
You can recognize Python's snake_case naming convention and write clear boolean names using conventional prefixes.