Keywords and Built-in Identifiers in Python

PythonBeginner
Practice Now

Introduction

In this lab, you will explore the fundamental concepts of Python's reserved words and pre-defined names. First, you will learn how to identify Python keywords, which are special words with specific meanings that cannot be used as variable or function names. We will use the built-in keyword module to list them.

Next, you will discover Python's built-in identifiers, such as functions and constants, that are always available in your code. Finally, you will see why it is crucial to avoid using keywords and built-in identifiers for your own names to prevent errors and keep your code clean and functional.

Identify Python Keywords

In this step, you will learn about Python keywords. Keywords, also known as reserved words, are the fundamental building blocks of the language's syntax. They have special meanings and cannot be used as names for your variables, functions, or any other identifiers.

Python provides a built-in module called keyword that makes it easy to see all the current keywords. Let's write a script to display them.

The necessary file, list_keywords.py, has already been created for you. Locate it in the file explorer on the left side of the WebIDE and click to open it.

Now, add the following code to the list_keywords.py file:

import keyword

## The kwlist attribute contains a list of all keywords.
print(keyword.kwlist)

After saving the file, open the integrated terminal in your WebIDE. You can do this by clicking Terminal -> New Terminal in the top menu.

Run your script by executing the following command in the terminal:

python ~/project/list_keywords.py

The output will be a list of all Python 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']

It is important to remember that these words are reserved. Python is case-sensitive, so while if is a keyword, IF is not. However, it is best practice to avoid using any variations of keywords as names to maintain code clarity.

Explore Python Built-in Identifiers

Now, let's explore Python's built-in identifiers. These are names that Python pre-defines for you, including common functions like print(), data types like int and str, and exceptions. They are always available in any Python script without needing an import statement.

You can view a list of all built-in identifiers by using the dir() function on a special object called __builtins__.

Open the file list_builtins.py from the file explorer. Add the following code to it:

## dir() returns a list of the names in the __builtins__ scope.
print(dir(__builtins__))

Save the file and run the script from the terminal:

python ~/project/list_builtins.py

You will see a long list of names printed to the console. Below is a truncated version of the output:

['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EncodingWarning', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

You will recognize many useful names in this list, such as len, input, list, and dict. In the next steps, we will see why you should avoid using these names for your own variables.

Avoid Using Keywords as Identifiers

In this step, you will see what happens when you try to use a Python keyword as a variable name. Because keywords are reserved for the language's structure, attempting to assign a value to them will cause the program to fail before it even runs.

Let's demonstrate this by trying to use the keyword with as a variable name.

Open the file keyword_error.py in the WebIDE editor. Add the following code, which is intentionally incorrect:

## This will cause an error because 'with' is a keyword.
with = 5
print(with)

Save the file and try to run it from the terminal:

python ~/project/keyword_error.py

Python will immediately stop and report a SyntaxError.

  File "/home/labex/project/keyword_error.py", line 2
    with = 5
    ^^^^
SyntaxError: invalid syntax

The error message SyntaxError: invalid syntax clearly indicates that the code is structured incorrectly. This happens because the Python interpreter recognizes with as a keyword that should start a with statement, not as a name that can hold a value. This rule applies to all keywords you listed in the first step.

Avoid Overwriting Built-in Identifiers

Unlike keywords, Python does not prevent you from reassigning built-in identifiers. However, doing so is a common source of bugs and should be avoided. When you assign a new value to a built-in name, you "hide" its original functionality, which can lead to unexpected errors.

Let's see what happens when we overwrite the built-in print function.

Open the file builtin_override.py in the WebIDE editor. Add the following code:

## Overwrite the built-in print function with an integer.
print = 5

## Now, try to use print() as a function.
print("hello")

Save the file and run it from the terminal:

python ~/project/builtin_override.py

This time, the script starts running but fails with a TypeError.

Traceback (most recent call last):
  File "/home/labex/project/builtin_override.py", line 5, in <module>
    print("hello")
TypeError: 'int' object is not callable

The error TypeError: 'int' object is not callable occurs because the name print no longer refers to the built-in printing function. Instead, it refers to the integer 5. Since you cannot "call" an integer like a function (using parentheses), the program crashes.

This demonstrates the danger of overwriting built-ins. It can break your code in non-obvious ways and make it difficult to debug. Always choose unique, descriptive names for your variables and functions to avoid these conflicts.

Summary

In this lab, you learned about two important categories of names in Python: keywords and built-in identifiers. You used the keyword module to list all of Python's reserved keywords and saw how trying to use them as variable names results in a SyntaxError.

You also explored the list of built-in identifiers and demonstrated the problems that arise from overwriting them, which can lead to TypeError and other runtime issues. The key takeaway is to always choose unique names for your variables and functions, avoiding both keywords and built-in names to ensure your code is robust, readable, and free of conflicts.