Python identifiers are names for variables, functions, classes, and other objects. They must follow language rules and should also be readable.
Understanding the Concept
An ordinary identifier may contain letters, digits, and underscores but cannot begin with a digit. Python keywords such as class and for cannot be used as ordinary identifiers. Names are case-sensitive. Python supports many Unicode identifier characters, but simple ASCII names are often easier to share across teams. Use the keyword module when you want to check whether a word is reserved. A valid identifier can still be a poor descriptive name.
When and Why You Would Use This
Try checking several candidate names. The methods and modules in the example provide an objective answer, rather than guessing based only on what looks familiar.
Practical Example
import keyword
candidate_names = ["customer_total", "3items", "class", "itemCount"]
for candidate_name in candidate_names:
print(candidate_name, candidate_name.isidentifier() and not keyword.iskeyword(candidate_name))
Understanding the Example
customer_total and itemCount are usable ordinary names, while 3items begins with a digit and class is a keyword. The naming style recommendation remains snake_case even when another name is technically valid.
Example Output
customer_total True
3items False
class False
itemCount True
Try It Yourself
Test five proposed variable names using str.isidentifier() and keyword.iskeyword().
Common Beginner Mistakes
- Starting identifiers with digits.
- Using reserved keywords as variables or function names.
- Assuming item_count and Item_Count are the same name.
Key Takeaways
- Identifiers must follow Python’s naming rules.
- Keywords are reserved for language syntax.
- Valid names should also describe their purpose clearly.