How to Check if a String Is a Valid Keyword in Python
Python reserves a set of special words called keywords (also known as reserved words) that have predefined meanings in the language. These keywords, like for, if, True, return, and lambda, cannot be used as variable names, function names, or identifiers. Attempting to do so results in a SyntaxError.
Knowing how to check whether a string is a Python keyword is useful when you're building code generators, linters, input validators, or educational tools. In this guide, you'll learn how to use Python's built-in keyword module to identify keywords, list all of them, and avoid common naming mistakes.
What Are Python Keywords?
Keywords are reserved words that the Python interpreter uses to understand the structure and logic of your code. They define control flow, logical operations, data types, and more.
Here's what happens if you try to use a keyword as a variable name:
for = 10
Output:
SyntaxError: invalid syntax
Python prevents you from assigning values to keywords because they serve a special purpose in the language's grammar.
Checking a Single String with keyword.iskeyword()
Python's built-in keyword module provides the iskeyword() function, which returns True if the given string is a Python keyword and False otherwise.
import keyword
print(keyword.iskeyword("for")) # True
print(keyword.iskeyword("hello")) # False
print(keyword.iskeyword("True")) # True
print(keyword.iskeyword("return")) # True
print(keyword.iskeyword("python")) # False
Output:
True
False
True
True
False
iskeyword() is case-sensitive. For example, "True" is a keyword, but "true" is not:
import keyword
print(keyword.iskeyword("True")) # True
print(keyword.iskeyword("true")) # False
print(keyword.iskeyword("FALSE")) # False
print(keyword.iskeyword("False")) # True
Output:
True
False
False
True
Checking Multiple Strings at Once
You can loop through a list of strings and classify each one as a keyword or not:
import keyword
words = ["for", "data", "elif", "elseif", "assert",
"True", "False", "model", "break", "lambda",
"try", "score", "class", "import", "config"]
keywords_found = []
non_keywords = []
for word in words:
if keyword.iskeyword(word):
keywords_found.append(word)
else:
non_keywords.append(word)
print(f"Keywords: {keywords_found}")
print(f"Non-keywords: {non_keywords}")
Output:
Keywords: ['for', 'elif', 'assert', 'True', 'False', 'break', 'lambda', 'try', 'class', 'import']
Non-keywords: ['data', 'elseif', 'model', 'score', 'config']
Listing All Python Keywords
If you need a complete list of Python's reserved keywords, the keyword module provides the kwlist attribute:
import keyword
print(f"Python {__import__('sys').version.split()[0]} has {len(keyword.kwlist)} keywords:\n")
for i, kw in enumerate(keyword.kwlist, 1):
print(f"{kw:12s}", end="\n" if i % 5 == 0 else "")
Output:
Python 3.11.2 has 35 keywords:
False None True and as
assert async await break class
continue def del elif else
except finally for from global
if import in is lambda
nonlocal not or pass raise
return try while with yield
The number of keywords may vary between Python versions. For example, async and await became full keywords in Python 3.7. Always use keyword.kwlist to get the accurate list for your current Python version.
Checking for Soft Keywords (Python 3.10+)
Starting with Python 3.10, Python introduced soft keywords, i.e. words like match and case that act as keywords only in specific contexts (such as structural pattern matching) but can still be used as variable names elsewhere.
import keyword
# Check soft keywords (Python 3.10+)
if hasattr(keyword, 'softkwlist'):
print(f"Soft keywords: {keyword.softkwlist}")
else:
print("Soft keywords are not available in this Python version.")
# 'match' is a soft keyword, not a hard keyword
print(f"Is 'match' a keyword? {keyword.iskeyword('match')}")
# You can still use 'match' as a variable name
match = 42
print(f"match = {match}")
Output (Python 3.12):
Soft keywords: ['_', 'case', 'match']
Is 'match' a keyword? False
match = 42
iskeyword() returns False for soft keywords because they are not fully reserved. Use keyword.softkwlist (Python 3.12+) or keyword.issoftkeyword() to check for them.
Practical Example: Validating Variable Names
A common use case is validating user-provided variable names. For instance, in a code generator or a dynamic configuration system. A valid variable name must follow Python's naming rules and must not be a keyword.
import keyword
def is_valid_variable_name(name):
"""Check if a string is a valid Python variable name."""
if not name.isidentifier():
return False, "Not a valid identifier (must start with a letter or underscore, contain only letters, digits, and underscores)."
if keyword.iskeyword(name):
return False, f"'{name}' is a reserved keyword."
return True, "Valid variable name."
test_names = ["my_var", "for", "2fast", "_private", "class", "data_set", "my-var", "True"]
for name in test_names:
is_valid, reason = is_valid_variable_name(name)
status = "✅" if is_valid else "❌"
print(f"{status} '{name}': {reason}")
Output:
✅ 'my_var': Valid variable name.
❌ 'for': 'for' is a reserved keyword.
❌ '2fast': Not a valid identifier (must start with a letter or underscore, contain only letters, digits, and underscores).
✅ '_private': Valid variable name.
❌ 'class': 'class' is a reserved keyword.
✅ 'data_set': Valid variable name.
❌ 'my-var': Not a valid identifier (must start with a letter or underscore, contain only letters, digits, and underscores).
❌ 'True': 'True' is a reserved keyword.
This function combines str.isidentifier() (which checks naming rules) with keyword.iskeyword() (which checks for reserved words) to provide complete validation.
Quick Reference
| Function / Attribute | Purpose | Returns |
|---|---|---|
keyword.iskeyword("word") | Check if a string is a keyword | True or False |
keyword.kwlist | List all Python keywords | list of strings |
keyword.softkwlist | List soft keywords (3.12+) | list of strings |
keyword.issoftkeyword("word") | Check if a string is a soft keyword (3.12+) | True or False |
str.isidentifier() | Check if a string is a valid identifier | True or False |
Conclusion
Python's keyword module makes it simple to check whether a string is a reserved keyword:
- Use
keyword.iskeyword()to check individual strings. It returnsTruefor reserved keywords andFalsefor everything else. - Use
keyword.kwlistto get the complete list of keywords for your Python version. - Combine
iskeyword()withstr.isidentifier()for full variable name validation. - For Python 3.10+, be aware of soft keywords like
matchandcasethat behave as keywords only in specific contexts.
These tools are essential when building code generators, linters, educational platforms, or any application that needs to validate Python identifiers programmatically.