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.

PythonSecurity Boundaries

Code

pythonsnippet
15 lines
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: keyword is 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

FAQ

Are there third-party dependencies?
`keyword` — install it with the package manager before running.