keyword
The Python keyword
module provides functionality to work with Python’s reserved words or keywords, which are words with a special meaning in the language’s syntax. In most cases, you can’t use these words as identifiers.
This module is useful for checking if a string is a reserved keyword and for getting a list of all current keywords.
Here’s a quick example:
>>> import keyword
>>> keyword.iskeyword("def")
True
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', ...]
Note: Python also has what are known as soft keywords, which you can use as identifiers in certain contexts.
Key Features
Frequently Used Classes and Functions
Object | Type | Description |
---|---|---|
keyword.iskeyword() |
Function | Returns True if the string is a keyword |
keyword.kwlist |
List | Holds the list of keywords used in Python |
keyword.issoftkeyword() |
Function | Returns True if the string is a soft keyword |
keyword.softkwlist |
List | Holds the list of soft keywords used in Python |
Examples
Checking if a string is a Python keyword:
>>> keyword.iskeyword("while")
True
>>> keyword.iskeyword("hello")
False
Retrieving the list of all Python keywords:
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', ...]
Retrieving the list of all Python soft keywords:
>>> keyword.softkwlist
['_', 'case', 'match', 'type']
Common Use Cases
- Validating identifiers in code editors or IDEs
- Syntax highlighting in text editors
- Generating code dynamically while avoiding reserved keywords
Real-World Example
Suppose you’re writing a script that generates Python variable names and you want to ensure that none of the generated names are Python keywords. You can use the keyword
module to filter out any reserved words.
>>> import keyword
>>> potential_names = ["class", "variable", "def", "data"]
>>> valid_names = [
... name for name in potential_names if not keyword.iskeyword(name)
... ]
>>> valid_names
['variable', 'data']
In this example, the keyword
module helps to ensure that only non-keyword names are used, avoiding syntax errors when the code is executed.
Related Resources
Tutorial
Python Keywords: An Introduction
Python keywords are the fundamental building blocks of any Python program. In this tutorial, you'll learn the basic syntax and usage of each of Python's thirty-five keywords and four soft keywords so you can write more efficient and readable code.
For additional information on related topics, take a look at the following resources:
- Exploring Keywords in Python (Course)
- Python Keywords: An Introduction (Quiz)
By Leodanis Pozo Ramos • Updated July 11, 2025