Shadowing built in Python variables
Python allows you to shadow built in variables: e.g., list, dict, set, range,….This can
lead to errors like 'int' object is not callable:
In [1]: range = 5
In [2]: for i in range(3):
...: i * 2
...:
----------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[2], line 1
----> 1 for i in range(3):
2 i * 2
TypeError: 'int' object is not callable
Avoid shadowing built in variables with suffixes #
For example:
_range = 5
Or just avoid built in variable names altogether.
Restore built in variables in the REPL #
I’ve only been caught by the shadowing variable issue in the REPL. Instead of restarting the REPL,
built in variables can be restored with del <variable_name>:
In [7]: range = 5
In [8]: del range
In [9]: for i in range(3):
...: print(i * 2)
...:
0
2
4
Tags: