On this page
  1. keyword
  2. Import
  3. Overview
  4. Quick Start
  5. Implementation Walkthrough
  6. 1. Sanitizing External Field Names into Valid Python Identifiers
  7. Gotchas & Boundaries
  8. Common Functions
  9. Constants & Attributes

keyword

Prev: json | Up: stdlib_module | Next: linecache
Rel: sys, sysconfig, builtins, warnings, dataclasses
Ref: docs.python.org — keyword
Tags: #public #python3 #stdlib


Import

import keyword

Overview

Authoritative lists and predicates for Python's reserved keywords (kwlist, iskeyword()) and context-sensitive soft keywords (softkwlist, issoftkeyword(), such as match, case, type, _). Use keyword when validating generated identifiers, building code generators, or checking field names before creating dynamic classes or dataclasses.

Quick Start

import keyword

assert keyword.iskeyword("async") is True
assert keyword.iskeyword("match") is False
assert keyword.issoftkeyword("match") is True

Implementation Walkthrough

1. Sanitizing External Field Names into Valid Python Identifiers

Combine str.isidentifier() with keyword.iskeyword() before binding external schema keys (like JSON/CSV headers) to Python attributes:

import keyword

def safe_identifier(name: str) -> str:
    cleaned = "".join(ch if ch.isalnum() or ch == "_" else "_" for ch in name)
    if not cleaned or cleaned[0].isdigit():
        cleaned = f"_{cleaned}"
    if keyword.iskeyword(cleaned):
        cleaned = f"{cleaned}_"
    return cleaned

assert safe_identifier("class") == "class_"
assert safe_identifier("2nd-item") == "_2nd_item"

Gotchas & Boundaries

Common Functions

Constants & Attributes

Linked from

Related notes