keyword | Python Standard Library – Real Python

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:

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

Examples

Checking if a string is a Python keyword:

Retrieving the list of all Python keywords:

Retrieving the list of all Python soft keywords:

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.

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: