Why does code like `str = str(...)` cause a TypeError, but only the second time?
Code like str = str(...)
causes a TypeError because it attempts to re-assign the built-in str
type to a new value, which is not allowed. This type of assignment is allowed in some programming languages, but not in Python. The TypeError will only occur on the second time because the first time it will override the built-in str function to the user defined variable and then in the second time it's trying to override the variable which is not allowed.
Here is an example of this happening:
str = "Hello, World!"
print(str) # Output: "Hello, World!"
str = str(123)
print(str) # Output: TypeError: 'str' object is not callable
You could use a different variable name instead of str
to avoid this issue and use str() without any problem.
my_str = "Hello, World!"
print(my_str) # Output: "Hello, World!"
my_str = str(123)
print(my_str) # Output: "123"