4.6 Keywords
What Python keywords are, the complete keyword list for Python 3.12, using help('keywords'), and why keywords can't be used as identifiers.
What Are Keywords?
What Is It?
Reserved words that are part of Python’s own syntax (if, for, def, class, …). The language grammar gives them special meaning, so they cannot be used as ordinary names.
Why Does It Matter?
Attempting to use a keyword as a variable name is a SyntaxError, not a warning.
>>> class = 5
File "<stdin>", line 1
class = 5
^^^^^
SyntaxError: invalid syntax
Complete Keyword List
Python 3.12 has 35 keywords, retrievable programmatically via the keyword module:
>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await',
'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except',
'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is',
'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try',
'while', 'with', 'yield']
>>> len(keyword.kwlist)
35
Python’s 35 keywords, grouped by purpose.
Hard Keywords vs Soft Keywords
Hard Keywords
Hard keywords are always reserved. The parser recognizes them wherever an identifier could otherwise appear, so names such as class, for, and return are invalid in every context.
class = "deployment" # SyntaxError: invalid syntax
Soft Keywords
Soft keywords are reserved only in specific grammar contexts. In Python 3.10 and later, match and case are soft keywords used by structural pattern matching. The underscore (_) also has special pattern-matching behavior. Python 3.12 adds type as a soft keyword for type alias statements.
match status:
case 200:
message = "ok"
case _:
message = "unexpected status"
# Outside a match statement, these names can still be used normally.
match = "rolling"
type = "service"
Use keyword.softkwlist when code must account for contextual keywords as well as the hard keyword list:
>>> import keyword
>>> keyword.softkwlist
['_', 'case', 'match', 'type']
The exact list is version-dependent. Check the interpreter that will run the code rather than hard-coding a count.
Keywords by Role
| Role | Keywords | Typical purpose |
|---|---|---|
| Decisions and loops | if, elif, else, for, while, break, continue, pass | Select paths and repeat work |
| Functions and generators | def, return, lambda, yield | Define callable code and produce values lazily |
| Classes and objects | class, del, is, in | Define types, remove bindings, and test identity or membership |
| Exceptions | try, except, else, finally, raise, assert | Detect, handle, raise, and validate failures |
| Imports and aliases | import, from, as | Load modules and assign local aliases |
| Context managers | with | Acquire and release resources predictably |
| Scope | global, nonlocal | Rebind names outside the current local scope |
| Boolean and special values | and, or, not, True, False, None | Combine conditions and represent values |
| Asynchronous code | async, await | Define and suspend asynchronous operations |
Checking Names Safely
An identifier must pass both checks: it must have valid identifier syntax and must not be reserved by the interpreter.
import keyword
def is_available_name(candidate: str) -> bool:
return candidate.isidentifier() and not keyword.iskeyword(candidate)
for candidate in ("service_name", "2services", "class"):
print(candidate, is_available_name(candidate))
Expected output:
service_name True
2services False
class False
str.isidentifier() checks the shape of a name; keyword.iskeyword() checks whether the interpreter reserves it. Neither check prevents shadowing a built-in such as list or type, so use clear project-specific names and follow 4.16 Coding Standards (PEP 8).
Practical DevOps Example
Keywords frequently appear in automation scripts that inspect command results and handle failures:
import subprocess
def check_service(service_name: str) -> str:
try:
result = subprocess.run(
["systemctl", "is-active", service_name],
check=True,
capture_output=True,
text=True,
)
except subprocess.CalledProcessError as error:
raise RuntimeError(f"Unable to inspect {service_name}") from error
else:
return result.stdout.strip()
finally:
print(f"Finished checking {service_name}")
Here, def, try, except, raise, from, else, and finally are keywords that define the control flow. The service name remains data supplied to the function, not a dynamically constructed piece of Python syntax.
How Python Handles a Keyword Error
Python parses source code before executing it. If a hard keyword appears where an identifier is required, parsing stops and no statements from that module run.
This is why a keyword naming error cannot be fixed with try/except: the try block itself cannot execute until the source has successfully parsed.
Using help('keywords')
How Is It Used?
The interactive help system lists and explains every keyword directly from the interpreter, without needing internet access:
>>> help("keywords")
Here is a list of the Python keywords. Enter any keyword to get more help.
False class from or
None continue global pass
...
Restrictions
Keywords cannot be used as variable, function, or class names. Use keyword.iskeyword() to check programmatically before using a name you’re unsure about:
>>> keyword.iskeyword("for")
True
>>> keyword.iskeyword("variable")
False
Keywords Are Not the Same as Built-ins
class is a keyword and cannot be assigned. list, type, and id are built-in names, not hard keywords, so Python permits them but shadowing them can break later code:
list = ["api", "worker"]
print(list("abc")) # TypeError: 'list' object is not callable
Use a descriptive name such as services instead. This distinction is a common interview follow-up.
Troubleshooting Checklist
When Python reports a keyword-related SyntaxError:
- Read the caret (
^) location, then inspect the complete statement around it. - Check whether a variable, function, parameter, or class has the same spelling as a hard keyword.
- Run
python -m py_compile your_script.pyto catch parse errors without executing the script. - Check the interpreter version with
python --version; keyword behavior can differ between Python versions. - Rename the identifier rather than trying to quote or escape it. Python has no escape syntax that turns a keyword into an ordinary identifier.
Quick Interview Answer
“Keywords are the 35 reserved words baked into Python’s grammar —
if,for,def,class,import, and so on. They can never be used as an identifier; trying raises aSyntaxErrorimmediately, not a runtime warning. You can list them at any time withkeyword.kwlistor check a specific name withkeyword.iskeyword().”
Common Mistakes
- Trying to name a variable
class,type, orlist—classis a hard keyword (fails outright);typeandlistare built-in names, not keywords, so they’re technically legal but silently shadow the built-in. - Assuming the keyword count never changes across versions — soft keywords such as
match,case,_, andtypebehave contextually and are reported separately bykeyword.softkwlist. - Trying to catch a keyword
SyntaxErrorat runtime — parsing happens before execution, so the source must be corrected first. - Treating a keyword as the same thing as a built-in — keywords are grammar tokens; built-ins are ordinary names initially provided by the built-in namespace.
Interview Follow-up Questions
- What is the difference between a keyword, a soft keyword, and a built-in name?
- How can you list Python keywords programmatically?
- Why can a
try/exceptblock not catchclass = 1? - What are
matchandcase, and why are they not inkeyword.kwlist? - How would you validate a user-provided name before generating Python source code?
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form