The use of list
, dict
, str
as variable names is a common newby 'mistake'.
I think that it is not a good practice for tutorials, but works OK in practice in this example. I would frown if code was presented to me with that parameters name however.
The more interesting thing to explore is WHY doesn't this tramp on the built-in str
function.
Look:
>>> str(123) # the built-in prior to the function 'f' declared
'123'
>>> def f(str): # Note 'str' as parameter
... return str[::-1]
...
>>> f('123') # function works...
'321'
>>> f(str(123)) # function 'f' works with the function 'str' prior
'321'
>>> str(123) # built-in 'str' still works...
'123'
The answer is that in f
the str
parameter overrides the built-in str
function only locally -- inside of f
. It is 'restored' to the built-in str
after the scope of f
is done.
Notice:
>>> def f(str):
... return str('123')[::-1]
...
>>> f(123)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
TypeError: 'int' object is not callable
Since you are calling int
inside f
you are referring to the parameter, not the function. It gets confusing and, hence, not a great idea to use the name of a built-in as a variable, parameter, etc whether local or global.