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:

Python
>>> import keyword
>>> keyword.iskeyword("def")
True
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', ...]

Key Features

  • Checks whether a string is a Python keyword using iskeyword() or a soft keyword using issoftkeyword()
  • Retrieves a list of all Python keywords and soft keywords

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:

Python
>>> keyword.iskeyword("while")
True
>>> keyword.iskeyword("hello")
False

Retrieving the list of all Python keywords:

Python
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'async', ...]

Retrieving the list of all Python soft keywords:

Python
>>> 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.

Python
>>> 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.

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.

basics python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated July 11, 2025