How to Get All Keywords in Python
Python is a versatile programming language with a rich set of built-in keywords. These keywords are reserved and cannot be used as variable names or identifiers. In this guide, you'll learn how to retrieve all Python keywords programmatically.
What Are Python Keywords?
Keywords in Python are special reserved words that convey a specific meaning to the compiler/interpreter. Examples include if
, else
, for
, while
, and def
.
Method 1: Using the keyword
Module
The easiest way to get all Python keywords is by using the built-in keyword
module. Here's how:
import keyword
# Get all keywords
all_keywords = keyword.kwlist
print(all_keywords)
This will output a list of all Python keywords for your current version.
Method 2: Checking If a Word Is a Keyword
You can also verify if a specific word is a keyword using the iskeyword()
function:
import keyword
print(keyword.iskeyword('if')) # Output: True
print(keyword.iskeyword('hello')) # Output: False
Method 3: Getting Soft Keywords (Python 3.10+)
Python 3.10 introduced soft keywords. To get these separately:
import keyword
if hasattr(keyword, 'softkwlist'):
print(keyword.softkwlist)
Why This Matters
Knowing how to access keywords programmatically helps in:
- Building code analysis tools
- Creating syntax highlighters
- Developing linters and validators
Conclusion
The keyword
module provides simple ways to access Python's reserved words. Whether you're building developer tools or just curious, these methods give you all the keywords in your Python version.