How to Check If a String Is a Valid Identifier in Python
When performing metaprogramming, processing user input for dynamic variable creation, or validating configuration files, you often need to check if a string can be used as a valid variable, function, or class name in Python. This is known as checking if a string is a valid identifier.
This guide explains the rules of Python identifiers and how to validate them programmatically using the built-in isidentifier() method and the keyword module.
Understanding Python Identifier Rules
Before writing code, it is important to know what constitutes a valid identifier in Python 3:
- Start Character: Must start with a letter (a-z, A-Z) or an underscore (
_). It cannot start with a number. - Body Characters: Can contain letters, numbers, and underscores.
- No Special Characters: Symbols like
@,$,-, or spaces are not allowed. - Case Sensitivity:
myVarandmyvarare different identifiers. - Reserved Keywords: Words like
if,class, orreturnare reserved and cannot be used as names, even if they fit the character rules.
Method 1: Using str.isidentifier()
Python strings have a built-in method .isidentifier() that returns True if the string adheres to syntax rules (points 1-3 above).
# ✅ Valid identifiers
var1 = "my_variable"
var2 = "_private"
var3 = "var123"
print(f"'{var1}' is valid? {var1.isidentifier()}")
print(f"'{var2}' is valid? {var2.isidentifier()}")
print(f"'{var3}' is valid? {var3.isidentifier()}")
Output:
'my_variable' is valid? True
'_private' is valid? True
'var123' is valid? True
Handling Invalid Strings
Use this method to detect syntax errors like starting with numbers or including spaces.
# ⛔️ Invalid identifiers
invalid_start = "1st_variable"
invalid_char = "my-variable"
invalid_space = "my variable"
print(f"'{invalid_start}' is valid? {invalid_start.isidentifier()}")
print(f"'{invalid_char}' is valid? {invalid_char.isidentifier()}")
print(f"'{invalid_space}' is valid? {invalid_space.isidentifier()}")
Output:
'1st_variable' is valid? False
'my-variable' is valid? False
'my variable' is valid? False
The Keyword Trap: The isidentifier() method does not check if a string is a reserved keyword. It only checks if the string contains valid characters.
Method 2: Checking for Reserved Keywords
Even if a string passes isidentifier(), it might still cause a SyntaxError if it is a reserved keyword (e.g., None, True, def). To check this, you must use the keyword module.
import keyword
# ⛔️ Warning: 'class' is syntactically valid characters, but logically invalid
reserved_word = "class"
print(f"Is 'class' syntactically valid? {reserved_word.isidentifier()}")
# ✅ Correct: Check if it is a keyword
is_reserved = keyword.iskeyword(reserved_word)
print(f"Is 'class' a reserved keyword? {is_reserved}")
Output:
Is 'class' syntactically valid? True
Is 'class' a reserved keyword? True
Robust Solution: Combining Both Checks
To ensure a string is truly safe to use as a variable name, you must verify that it is syntactically correct AND not a reserved keyword.
import keyword
def is_valid_variable_name(name):
return name.isidentifier() and not keyword.iskeyword(name)
# Test cases
test_names = ["my_var", "123var", "class", "my-var", "yield"]
print(f"{'Name':<10} | {'Valid?':<6}")
print("-" * 20)
for name in test_names:
valid = is_valid_variable_name(name)
print(f"{name:<10} | {valid}")
Output:
Name | Valid?
--------------------
my_var | True
123var | False
class | False
my-var | False
yield | False
Python 3 supports Unicode characters in identifiers. str.isidentifier() handles this correctly. For example, π = 3.14 is valid Python, and "π".isidentifier() returns True.
Conclusion
To check if a string is a valid identifier in Python:
- Use
str.isidentifier()to check for character validity (no starting numbers, no special symbols). - Use
keyword.iskeyword()to ensure the string isn't reserved. - Combine both for a robust validation function suitable for metaprogramming or sanitizing inputs.