I have the following simple python script, test_type.py
#!/usr/bin/env python
for type, path in [('dir', 'c:/users')]:
print(f'{type}={path}')
mystring = 'this string'
if type(mystring) == str:
print(mystring)
when I run it, I got error
dir=c:/users
Traceback (most recent call last):
File "test_type.py", line 8, in <module>
if type(mystring) == str:
TypeError: 'str' object is not callable
The error is likely due to using 'type' as both a local variable and a build-in function name, because when I comment out the for loop, the error is gone.
But why is this a problem? The first 'type' is a local variable; it shouldn't pollute the namespace.
Background:
The test script is extracted from a big program I am working on.
I tested the script in both python 3.8.5 on ubuntu and 3.10.2 on windows 10. Both behaves the same.
I can change my program to use a different variable name but I'd like to know the reason because I could inadvertently bump into similar problem again. It took me a while to narrow it down.
Thank you