Python Keywords
Python · Getting Started
Theory
Keywords are words that Python reserves for its own grammar, such as if, else, for, while, def, class, return, import, True, False and None. The parser recognises them before anything else, so you cannot use a keyword as a variable, function or class name: writing class = 5 is a SyntaxError. The standard library module keyword holds the full list in keyword.kwlist, and keyword.iskeyword('for') checks a single word.
A few words are soft keywords, for example match and case. They act as keywords only in specific positions (inside a match statement) and remain usable as ordinary names elsewhere, which is why keyword.iskeyword('match') returns False. Also note that common names like print, len, sum, list and str are not keywords at all; they are built-in functions and types, so Python lets you reuse them, but doing so hides the original.
Why we use it
Keywords are the fixed vocabulary that gives Python code its structure. Knowing them helps you read any program, understand SyntaxError messages, and avoid choosing a variable name the language already owns.
When to use it
Check keyword.kwlist or keyword.iskeyword() when a name gives a strange SyntaxError. Avoid reusing built-in names like list, sum or str as variables too; they are not keywords, but shadowing them causes confusing bugs later.
How it works
- You type a name, e.g. class = 5
- The parser checks the word against the keyword list
- Is it a hard keyword? Yes: SyntaxError: the word is reserved. No: Treat it as an ordinary name.
- Is it a built-in like list or sum? Yes: Allowed, but it hides the built-in from now on. No: Safe to use.
- Name is bound to the value
Syntax
import keyword
keyword.kwlistExample
import keyword
print(keyword.kwlist)Key points
- Keywords cannot be used as names: class = 5 raises a SyntaxError
- True, False and None are keywords and are capitalised
- len(keyword.kwlist) shows how many hard keywords your Python version has
- match and case are soft keywords, special only inside a match statement
- print, len and sum are built-ins, not keywords, so do not reuse them as names