How to fix redefinition of str?

Question:

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?

Asked By: J0e3gan

||

Answers:

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.

Answered By: satoru
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.