I have some code like:
def example(parameter):
global str
str = str(parameter)
print(str)
example(1)
example(2)
The first call to example works, but then the second time around I get an error like:
Traceback (most recent call last):
File "test.py", line 7, in <module>
example(2)
File "test.py", line 3, in example
str = str(parameter)
TypeError: 'str' object is not callable
Why does this happen, and how can I fix it?
If you are in an interactive session and encountered a problem like this, and you want to fix the problem without restarting the interpreter, see How to restore a builtin that I overwrote by accident?.
Where the code says:
You are redefining what
str()means.stris 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
globalstatement.Note that if you used code like this at the Python REPL, then the assignment to the global
strwill persist until you do something about it. You can restart the interpreter, ordel str. The latter works becausestris not actually a defined global variable by default – instead, it’s normally found in a fallback (thebuiltinsstandard library module, which is specially imported at startup and given the global name__builtins__).