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:
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__
).