Skip to content

How to Check If a String Is a Valid Identifier in Python

Learn how to validate Python variable, function, or class names programmatically using str.isidentifier() and the keyword module to avoid syntax errors.

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:

  1. Start Character: Must start with a letter (a-z, A-Z) or an underscore (_). It cannot start with a number.
  2. Body Characters: Can contain letters, numbers, and underscores.
  3. No Special Characters: Symbols like @, $, -, or spaces are not allowed.
  4. Case Sensitivity: myVar and myvar are different identifiers.
  5. Reserved Keywords: Words like if, class, or return are 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).

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_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

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

reserved_word = "class"
print(f"Is 'class' syntactically valid? {reserved_word.isidentifier()}")

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_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

Conclusion

To check if a string is a valid identifier in Python:

  1. Use str.isidentifier() to check for character validity (no starting numbers, no special symbols).
  2. Use keyword.iskeyword() to ensure the string isn't reserved.
  3. Combine both for a robust validation function suitable for metaprogramming or sanitizing inputs.
Navigation