Experimenting with the Python interpreter, I unwittingly assigned a string to str
as follows:
str = 'whatever'
Later in the same session I entered another statement with a call to str()
, say...
double_whatever = str(2) + ' * whatever'
..., and got the error TypeError: 'str' object is not callable
(instead of the expected output '2 * whatever'
). A related SO answer helped me to quickly see the mistake I made.
However, I am still unclear how to fix calls to str()
in the affected session. Of course I could exit the Python interpreter and start another session, but I am curious how to avoid that.
So far I have confirmed that...
double_whatever = __builtins__.str(2) + ' * whatever' # => '2 * whatever'
...still works like I want; but I am unclear how to get back to not needing the __builtins__.
qualification.
How can I fix my unintentional redefinition of str
so that my calls to str()
in the Python-interpreter session work again?
Just delete your overriding str
:
del str
Read http://www.diveintopython.net/html_processing/locals_and_globals.html for an explanation of how Python finds a variable for you.
The basic idea is that the namespace where you define variables is searched first, so if you define a variable with the name str
, the built-in
one is overridden.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With