str.isidentifier()
Test whether a string has the SHAPE of a Python identifier — not whether you can use it as a variable name.
Demo
isidentifier() checks the SHAPE of a Python identifier: starts with a Unicode letter or underscore, followed by letters, digits, or underscores. Empty returns False. THE surprise: reserved keywords like "for", "class", "def" all pass because they have identifier shape — but assigning to them would be a SyntaxError. For a full "can I use this as a variable name" test, combine with keyword.iskeyword().
Common patterns
if not name.isidentifier(): raise ValueError("must be a valid Python identifier")
import keyword def is_usable_name(s): return s.isidentifier() and not keyword.iskeyword(s)
if attr.isidentifier(): setattr(obj, attr, value) else: obj.__dict__[attr] = value
Examples
Pitfalls
"class".isidentifier()
import keyword "class".isidentifier() and not keyword.iskeyword("class")
"my-name".isidentifier()
"my_name".isidentifier()
"1st".isidentifier()
"_1st".isidentifier()
"π".isidentifier()
name.isascii() and name.isidentifier()
When to use
- Validating user-provided field or attribute names
- Safety check before dynamic attribute access
- Config-file key validation
- Combining with keyword.iskeyword for full "usable name" check
- You need to reject reserved words → also check keyword.iskeyword
- You need ASCII-only names → combine with str.isascii
- You want lowercase snake_case only → regex or a custom validator
- Rich Unicode restrictions → third-party library or explicit character set
Notes
FAQ
Because isidentifier tests the SHAPE — starts with a letter or underscore, followed by letters, digits, or underscores. "for" matches that shape. Python rejects it as a variable name at parse time, not at method-call time. For a "usable as a variable name" check, add `keyword.iskeyword` to the test.