Sub topic 2
Choosing valid and readable names
This chapter assumes you can run Python code, use print(), and know that an assignment like count = 3 binds a name to an object. Here we cover which names Python accepts, which it accepts but you should avoid, and how to pick names that make code easy to read.
The rules Python enforces
A name (also called an identifier) must follow these rules:
- It can contain letters, digits, and underscores.
- It cannot start with a digit.
- It is case-sensitive:
totalandTotalare different names. - It cannot be a reserved keyword such as
if,for,class,None, orTrue. - It cannot contain spaces, hyphens, or other operators.
Letters are not limited to ASCII. Python 3 accepts Unicode letters, so café and größe are valid. Python normalizes identifiers with NFKC, so visually similar characters can silently become the same name. Stick to ASCII in shared code unless your team has agreed otherwise.
You can test a candidate with str.isidentifier() and the keyword module. isidentifier() alone is not enough, because it returns True for keywords.
import keyword
candidates = ["total", "_cache", "2fast", "first-name",
"class", "class_", "café", "match", "total_2"]
for word in candidates:
ok = word.isidentifier() and not keyword.iskeyword(word)
print(f"{word!r:14} valid name: {ok}")The output marks 2fast, first-name, and class as invalid. Everything else passes, including match. The word match is a soft keyword. It has a special meaning only inside a match statement, so you can still use it as a name. keyword.softkwlist lists the soft keywords.
Using an invalid name is a SyntaxError at compile time, before any of your code runs:
2fast = 10class = "math"Both fail with SyntaxError: invalid syntax. The error is raised for the whole file, so no earlier line runs either.
Case sensitivity
Two names that differ only in capitalization are unrelated:
Total = 10
total = 20
print(Total, total)This prints 10 20. A misspelled capital is a common source of NameError, which Python raises when it looks up a name that has not been bound. Treat the error text as a hint to check spelling and case first.
Valid but harmful: shadowing built-ins
Built-in names such as list, str, sum, max, min, id, type, input, and len are ordinary names that Python looks up after your own. If you bind one of them yourself, your binding wins in that scope. This is called shadowing. Python does not warn you.
list = [1, 2, 3]
try:
list("abc")
except TypeError as e:
print("TypeError:", e)
del list
print(list("abc"))The first call fails with TypeError: 'list' object is not callable, because list now refers to a list object, not the built-in class. After del list removes the module-level binding, the built-in becomes visible again and the last line prints ['a', 'b', 'c'].
Shadowing often appears far from where you caused it. You assign sum = 0 at the top of a file, and an hour later sum(prices) fails. Prefer a more specific name such as running_total. For a name that is hard to improve, add a trailing underscore: type_, id_, class_.
Conventions from PEP 8
PEP 8 is Python's style guide. Its naming conventions are not enforced by the interpreter, but nearly all Python code follows them, so breaking them makes your code look foreign.
| Kind of name | Convention | Example |
|---|---|---|
| Variables, functions, methods | `lower_snake_case` | `unit_price`, `read_config` |
| Constants (by convention, never reassigned) | `UPPER_SNAKE_CASE` | `MAX_RETRIES` |
| Classes | `CapWords` | `InvoiceLine` |
| Modules and packages | short, lowercase | `utils`, `payments` |
| Internal use | one leading underscore | `_cache` |
| Avoid a keyword clash | one trailing underscore | `class_` |
| Name mangling inside classes | two leading underscores | `__secret` |
| Special methods defined by Python | double underscores both sides | `__init__` |
Python has no true constants. MAX_RETRIES = 3 is a signal to readers, and the language still lets you reassign it.
A single leading underscore means "internal, not part of the public interface". It also has one practical effect: from module import * skips such names. A lone _ is conventionally a throwaway name, for example for _ in range(3):. In the interactive interpreter, _ also holds the last printed result.
Avoid the single letters l, O, and I as names. In many fonts they look like 1 and 0.
Writing names that read well
A valid name can still be a poor one. These habits keep code readable:
- Name what the object means, not what type it is. Prefer
unit_pricetofloat1ornumber. - Match length to scope. A loop variable used for two lines can be
iorrow. A module-level value used across a file needs a longer name. - Use plural names for collections and singular names for items:
for student in students:. - Start boolean names with a verb such as
is_,has_, orcan_:is_empty,has_discount. - Put the unit in the name when it is not obvious:
timeout_seconds,distance_km. This prevents mistakes that no type checker can catch. - Avoid abbreviations that only you understand.
cust_ord_cntcosts the reader time thatorder_countdoes not. - Do not make names differ only by case or by a trailing digit, as with
dataanddata2. Describe what makes them different.
Here is the same calculation written twice. Both versions give the same result:
# Hard to read
x = 49.5
y = 3
z = x * y * 1.2
# Easier to read
unit_price = 49.5
quantity = 3
TAX_FACTOR = 1.2
order_total = unit_price * quantity * TAX_FACTOR
print(order_total)The second version tells the reader what each number means. When the tax rate changes, a reader knows which line to edit.
Names are bindings, not labels on boxes
A name's validity says nothing about the object it refers to. As an earlier chapter showed, assignment binds a name to an object. Choosing a good name therefore describes the role the object plays in your program, and a rebinding such as count = "three" changes that role without any error. If a name could refer to both a number and a string, that is a design smell, and a clearer pair of names such as count and count_text avoids it.
Common errors
SyntaxErrorafter writing a name with a hyphen, such asfirst-name = "Ada". Python reads this as a subtraction. Usefirst_name.NameErrorfrom a misspelled or differently capitalized name.TypeError: 'x' object is not callableafter shadowing a built-in function.- Reassigning a constant by accident. The language allows it, so rely on review or a linter.
- Unexpected behaviour from look-alike Unicode characters. Two names that look identical on screen may be different, or may normalize to the same name.
Exercise
Which of these are valid Python names, and which of the valid ones would you change anyway? user_name, 3rd_place, max, is-ready, else, _total
Show answer
Valid: user_name, max, and _total. Invalid: 3rd_place (starts with a digit), is-ready (the hyphen is parsed as subtraction), and else (a keyword). Of the valid names, max is a poor choice because it shadows the built-in max() function. Use something like max_value or max_. _total is acceptable, but the leading underscore tells readers it is internal, so use it only if that is what you mean.
Exercise
A script starts with sum = 0. Later, sum([1, 2, 3]) raises TypeError: 'int' object is not callable. Explain the cause and give two ways to fix it.
Show answer
The assignment sum = 0 binds the name sum to an int, which shadows the built-in sum function. Calling it then tries to call an int. Fix it by renaming the variable (for example running_total = 0), or by removing the binding with del sum. Renaming is better, because it also removes the confusion for later readers.