5 Best Ways to Check if a Given Word is a Python Keyword

Rate this post

πŸ’‘ Problem Formulation: Python keywords are reserved words that cannot be used as identifiers for variables, functions, classes, or other objects. If a programmer inadvertently tries to do so, it will cause a syntax error. For instance, if someone attempts to declare a variable with the name class, which is a Python keyword, this leads to an error. The goal is to verify if a given word, such as “async”, is a Python keyword before using it. The desired output is a Boolean value: True if the word is a keyword, False otherwise.

Method 1: Using the keyword Module

The keyword module in Python’s standard library provides a list of all the current keywords. By using the keyword.iskeyword() function, you can check if a string is one of these reserved keywords. It is a straightforward and reliable method to solve our problem.

Here’s an example:

import keyword

def is_keyword(word):
    return keyword.iskeyword(word)

print(is_keyword("for"))
print(is_keyword("football"))

Output:

True
False

This code snippet defines a function is_keyword that leverages the keyword.iskeyword() function to check if the provided argument word is a Python keyword. The example shows that “for” is a keyword, whereas “football” is not.

Method 2: Checking Against the Keyword List

A list of all current Python keywords is maintained within the keyword.kwlist attribute. By directly checking if the string is in this list, you can confirm whether it is a reserved keyword or not.

Here’s an example:

import keyword

def is_keyword(word):
    return word in keyword.kwlist

print(is_keyword("while"))
print(is_keyword("whilst"))

Output:

True
False

The function is_keyword() checks if the string word exists in keyword.kwlist. “while” is identified as a keyword correctly, while “whilst” is not a keyword in Python.

Method 3: Using the tokenize Module

The tokenize module can categorize different parts of Python code. It can be used to verify if a certain string corresponds to a RESERVED_KEYWORD which implies it being a Python keyword.

Here’s an example:

import tokenize

def is_keyword(word):
    return tokenize.tok_name[tokenize.NAME] == 'NAME' and not word.isidentifier()

print(is_keyword("def"))
print(is_keyword("define"))

Output:

True
False

This code uses the tokenize module to check if the word is classified as a NAME token but is not a valid identifier, which would mean it’s a keyword. The string “def” is recognized as a keyword, while “define” is not.

Method 4: Exception Handling Approach

By attempting to execute a dynamic code using the exec() function containing the word, and catching any syntax errors, you can infer if the word is a keyword. This method is less conventional and not recommended for production code.

Here’s an example:

def is_keyword(word):
    try:
        exec(f"{word} = 1")
        return False
    except SyntaxError:
        return True

print(is_keyword("if"))
print(is_keyword("iffy"))

Output:

True
False

In this code, we try assigning a value to a variable named after word. If a SyntaxError is raised, it likely means the word is a keyword; otherwise, it is not. “if” raises an error and is correctly determined to be a keyword, whereas “iffy” does not.

Bonus One-Liner Method 5: Using the compile() Function

The compile() function converts a source string into a code object, which can then be executed. If compiling a string as an expression raises a SyntaxError, it’s probable that the word is a keyword.

Here’s an example:

is_keyword = lambda word: not compile(word, '', 'eval')
print(is_keyword("import"))
print(is_keyword("important"))

Output:

True
False

The provided lambda function tries to compile the word and relies on a SyntaxError being raised to identify a keyword. “import” is confirmed as a keyword, while “important” is not.

Summary/Discussion

  • Method 1: Using the keyword Module. It’s the standard and most straightforward approach. Strongly integrated with the Python language. It’s the recommended method.
  • Method 2: Checking Against the Keyword List. Very direct and easily understandable. Utilizes built-in library resources. Slightly less elegant than using keyword.iskeyword().
  • Method 3: Using the tokenize Module. Offers a deeper insight into Python’s tokenization process. It is more complicated and not as intuitive for simple keyword checks.
  • Method 4: Exception Handling Approach. A rather unconventional and hacky way of determining keywords. Not safe for all use cases and can have unexpected consequences.
  • Bonus One-Liner Method 5: Using the compile() Function. Crafty and concise but relies on catching exceptions, which isn’t always a best practice for code readability and maintainability.