W3docs

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.

Code like str = str(...) causes a TypeError because it shadows the built-in str type with a string variable. Python allows variable reassignment, but once str is reassigned, the name no longer refers to the built-in constructor. On the second line, str(123) tries to call the string variable as a function, which triggers the error. This occurs due to Python's LEGB name resolution rule: the local assignment hides the built-in str in the current scope.

Here is an example of this happening:

TypeError case in Python

str = "Hello, World!"
print(str) # Output: "Hello, World!"

str = str(123) # RHS `str` now refers to the string variable, not the built-in type
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.

avoid TypeError in Python

my_str = "Hello, World!"
print(my_str) # Output: "Hello, World!"

my_str = str(123)
print(my_str) # Output: "123"