Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix redefinition of str? [duplicate]

Tags:

python

string

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?

like image 392
J0e3gan Avatar asked Jan 09 '23 06:01

J0e3gan


1 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.

like image 191
satoru Avatar answered Jan 15 '23 13:01

satoru