Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Reserved words in Python PREMIUM

Trey Hunner smiling in a t-shirt against a yellow wall
Trey Hunner
3 min. read 2 min. video Python 3.9—3.13
Python Morsels
Watch as video
02:23

Let's talk about Python's keywords (not to be confused with keyword arguments).

Reserved words cannot be used as variable names

A reserved word (a.k.a. a keyword) is a word that cannot be used as a variable name.

For example, we can't use class as a variable, because class is reserved:

>>> class = 0
  File "<stdin>", line 1
    class = 0
          ^
SyntaxError: invalid syntax

We also can't use return as a variable name:

>>> return = 0
  File "<stdin>", line 1
    return = 0
           ^
SyntaxError: invalid syntax

Or import:

>>> import = 0
  File "<stdin>", line 1
    import = 0
           ^
SyntaxError: invalid syntax

Or continue:

>>> continue = 0
  File "<stdin>", line 1
    continue = 0
             ^
SyntaxError: invalid syntax

These names are reserved because they all mean something special in Python.

Reserved words are part of Python's syntax, so using them as variables might confuse other Python programmers. But more importantly, it might confuse the Python interpreter as it tries to parse our code.

Python's built-ins are not reserved words

Python only has a few dozen reserved words: 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.

We can see them all of Python's keywords by looking at the kwlist attribute in Python's keyword module:

>>> import keyword
>>> print(*keyword.kwlist, sep=", ")
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

Note that Python's many built-in functions are not in that list!

But don't shadow the built-ins

Even though there's a built-in list function in Python:

>>> list
<class 'list'>

We're allowed to use list as a variable name:

>>> list = ['apple', 'banana', 'cherry']

Though, naming a variable list might cause some problems. Even though you can use list as a variable, you probably shouldn't.

If we name a variable list, we won't be able to use the list function anymore:

>>> list = ['apple', 'banana', 'cherry']
>>> numbers = list(range(10))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable

We've just shadowed the name list. That doesn't mean that we've overwritten the list function, it just means that it's inaccessible right now because we've stuck another variable in front of it that happens to have the same name.

We've made a global variable called list:

>>> list
['apple', 'banana', 'cherry']

If we delete that variable, we'll have access to the list function once again:

>>> del list
>>> numbers = list(range(10))
>>> numbers
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Python has a separate scope for built-in functions and classes. We had just made a global variable that shadowed an already existing built-in variable with the same name.

You can see every built-in name in Python by inspecting the builtins module:

>>> import builtins
>>> print(*dir(builtins), sep=", ")
ArithmeticError, AssertionError, AttributeError, BaseException, BaseExceptionGroup, BlockingIOError, BrokenPipeError, BufferError, BytesWarning, ChildProcessError, ConnectionAbortedError, ConnectionError, ConnectionRefusedError, ConnectionResetError, DeprecationWarning, EOFError, Ellipsis, EncodingWarning, EnvironmentError, Exception, ExceptionGroup, 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

Many of the built-in variables in Python are exceptions, which start with a capital letter.

Some of them are also dunder variables, which start and end with two underscores (__):

>>> import builtins
>>> print(*dir(builtins), sep=", ")
... __build_class__, __debug__, __doc__, __import__, __loader__, __name__, __package__, __spec__, ...

Python has about 70 builtins that aren't exceptions or dunder variables:

>>> import builtins
>>> print(*[name for name in dir(builtins) if name[0].islower()], sep=", ")
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

See built-in functions for more on Python's many built-in functions.

While you can shadow built-in names in Python, you probably should avoid it when possible.

Name your variables carefully

Python has about three dozen names that cannot be used as valid variable names. Those are keywords or reserved words.

Python also has dozens of built-in functions that you should also avoid using as variable names when possible.

Python Morsels
Watch as video
02:23
This is a free preview of a premium screencast. You have 2 previews remaining.