isidentifier Guards Dynamic Field Names
Gate user-supplied field names behind str.isidentifier and keyword.iskeyword or issoftkeyword so dynamic attributes never collide with reserved syntax.
Code
import keyword
# User-supplied field names (CSV headers, JSON keys, CLI flags mapped
# onto attributes) must pass two checks before becoming attribute
# names: identifier syntax, and not being a reserved word
def safe_field(name):
if not name.isidentifier():
return f'reject {name!r}: not an identifier'
if keyword.iskeyword(name) or keyword.issoftkeyword(name):
return f'reject {name!r}: reserved word'
return f'accept {name}'
for candidate in ['order_id', '2fa', 'user-name', 'class', 'case', 'None']:
print(safe_field(candidate))How it works
The code’s whole job belongs to the function safe_field.
Repetition is confined to for candidate in ['order_id', '2fa', 'user-name', 'class', 'case', 'None'] — the rest of the file is straight-line.
What to watch for
- Plan for an install step:
keywordis a real dependency, resolved by the package manager.
Putting it to use
The main signature reads def safe_field(name)
Import safe_field from the file and call it — the rest of the code is implementation detail.
Core lines
for candidate in ['order_id', '2fa', 'user-name', 'class', 'case', 'None']:
print(safe_field(candidate))
def safe_field(name):
if not name.isidentifier():
return f'reject {name!r}: not an identifier'
if keyword.iskeyword(name) or keyword.issoftkeyword(name):
return f'reject {name!r}: reserved word'
return f'accept {name}'
Interactive Tools for This Topic
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Argon2id Hash InfoEstimate Argon2id password-hash latency and memory usage, and check your parameters against OWASP 2024 minimum and recommended settings.
FAQ
- Are there third-party dependencies?
- `keyword` — install it with the package manager before running.
Report a problem with this exampleOpens a pre-filled issue on GitHub.