I found out about this by accident today when I noticed that a piece of Python code had used the built-in function all
as a variable identifier to store the result of a list comprehension and it didn't throw an error, so I tried the following:
type('abc')
Out[1]: str
type('abc') == str
Out[2]: True
str = int
type('abc') == str
Out[4]: False
type('abc')
Out[5]: str
type = [1,2,3]
type('abc')
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-7-a74a7df76db1> in <module>()
----> 1 type('abc')
TypeError: 'list' object is not callable
Hopefully, it's a valid question when I ask why this behavior is allowed in Python.
Or better yet, how do I make sure that a built-in function like str
is really str
and not say, int
so str(123)
won't be evaluated as int(123)
by accident?