Sub topic 2
Choosing valid and readable names
This chapter assumes you can run Python code and use print(). It also assumes you know that name = value binds a name to an object. Here you learn which names Python accepts and which names other programmers can read easily.
The rules Python enforces
A name, also called an identifier, must follow these rules:
- It may contain letters, digits, and underscores.
- It must not start with a digit.
- It is case-sensitive, so
totalandTotalare different names. - It must not be a reserved keyword such as
class,if,for, orNone.
Python also accepts non-ASCII letters, so café is valid. Stick to ASCII in shared code, because other people have to type your names.
You can check a candidate with str.isidentifier() and the keyword module:
import keyword
for candidate in ["total", "_cache", "user2", "2fast", "my-var", "class", "café"]:
ok = candidate.isidentifier() and not keyword.iskeyword(candidate)
print(f"{candidate!r:10} {ok}")"class" needs the second check. It has the right shape for an identifier, so isidentifier() returns True, but it is reserved. The output shows False for '2fast', 'my-var', and 'class'.
Conventions from PEP 8
Python does not enforce these conventions. Almost every Python project follows them, so readers expect them.
| Kind of name | Style | Example |
|---|---|---|
| Variable, function | `snake_case` | `item_count`, `read_config` |
| Constant | `UPPER_SNAKE_CASE` | `MAX_RETRIES` |
| Class | `CapWords` | `OrderItem` |
| Internal use | leading underscore | `_cache` |
A leading underscore only signals "internal". It does not make the name private. A single _ is often used for a value you intend to ignore.
Readable names
A good name says what the object means, not what type it has. Compare these two lines:
d = 86400
seconds_per_day = 86400Prefer seconds_per_day over d. Avoid names that are easy to misread, such as l (lowercase L), O, and I. Short names like i or x are fine for a loop counter or a math formula, where the context is obvious.
Do not shadow built-ins
Names like list, str, sum, max, and type are not keywords, so Python lets you reuse them. Reusing one hides the built-in in your scope. This is called shadowing.
numbers = [3, 1, 2]
print(sum(numbers))
sum = 10
try:
print(sum(numbers))
except TypeError as e:
print("TypeError:", e)
del sum
print(sum(numbers))After sum = 10, the name sum is bound to an integer, so calling it fails with 'int' object is not callable. Deleting the module-level name with del makes the built-in visible again. The better fix is to pick a different name from the start, such as total or sum_value.
Common errors
SyntaxError: invalid syntaxon a line likeclass = 5. You used a keyword as a name.SyntaxErroron2fast = 1. A name cannot start with a digit.NameErrorafter a typo or a case mismatch.Countandcountare different names.- A
TypeErrorsaying an object is "not callable". You probably shadowed a built-in function.
Exercise
Which of these are valid, unreserved names: _temp, for, 3rd_place, max_value, Max-Value? Which one would you avoid even though Python accepts it, and why?
Show answer
_temp and max_value are valid. for is a keyword, 3rd_place starts with a digit, and Max-Value contains a hyphen. max_value is acceptable because it differs from the built-in max. Names such as max or list are valid but should be avoided, because they shadow built-ins.