Why does code like `str = str(…)` cause a TypeError, but only the second time?

Where the code says:

global str
str = str(parameter)

You are redefining what str() means. str is the built-in Python name of the string type, and you don’t want to change it.

Use a different name for the local variable, and remove the global statement.

Note that if you used code like this at the Python REPL, then the assignment to the global str will persist until you do something about it. You can restart the interpreter, or del str. The latter works because str is not actually a defined global variable by default – instead, it’s normally found in a fallback (the builtins standard library module, which is specially imported at startup and given the global name __builtins__).

Leave a Comment