On this page
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
isidentifier()returnsTruefor keywords:"for".isidentifier()isTrue, so always checknot keyword.iskeyword(s)as well when validating variable names.- Soft keywords are valid variable names:
match,case,type, and_are only keywords in specific grammatical positions;iskeyword("match")is intentionallyFalse. - Version-dependent:
kwlistandsoftkwlistreflect the running Python interpreter's grammar.
Common Functions
- keyword.iskeyword() —
iskeyword(object, /)— x.contains(y) <==> y in x. - keyword.issoftkeyword() —
issoftkeyword(object, /)— x.contains(y) <==> y in x.
Constants & Attributes
keyword.kwlist(list) =['False', 'None', 'True', 'and', 'as', 'assert', 'async',...keyword.softkwlist(list) =['_', 'case', 'match', 'type']
Linked from
Related notes
- tuts/python3/stdlib_module/json Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/keyword/iskeyword Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/keyword/issoftkeyword Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/linecache Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/stdlib_module Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/builtins Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/dataclasses Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/sys Linked here; shared tags: #stdlib
- tuts/python3/stdlib_module/sysconfig Linked here; shared tags: #stdlib