4

I doing some work inside the Python REPL and I redefined one of the primitive callable's.

i.e list = [] will prevent tuple = list((1,2,3)) from working anymore.

Aside from restarting the REPL is there a way to 'recover' or reassign list to its default value?

Maybe there is an import or a super class? Or would it be forever lost and stuck with what I assigned it until I restart the REPL?

Mark N
  • 326
  • 2
  • 13

1 Answers1

6

You can delete the name del list

In [9]: list = []    
In [10]: list()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-8b11f83c3293> in <module>()
----> 1 list()

TypeError: 'list' object is not callable    
In [11]: del list    
In [12]: list()
Out[12]: []

Or list = builtins.list for python3:

In [10]: import builtins
In [11]: list = []    
In [12]: list()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-12-8b11f83c3293> in <module>()
----> 1 list()

TypeError: 'list' object is not callable    
In [13]: list = builtins.list    
In [14]: list()
Out[14]: []

For python 2:

In [1]: import __builtin__    
In [2]: list = []    
In [3]: list()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-8b11f83c3293> in <module>()
----> 1 list()    
TypeError: 'list' object is not callable  
In [4]: list = __builtin__.list  
In [5]: list()
Out[5]: []
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • Thank you, this works! Are there any other ways that might also work or is this the only one? – Mark N Jun 19 '15 at 20:01
  • There are (`list = __builtins__.list`, `list = type([])`) but Padraic's method is better because the others just shadow the builtin by a local name that happens to be the same as the builtin; his solution removes the shadowing. – RemcoGerlich Jun 19 '15 at 20:02
  • @MarkN, yes added a way using builtin.list but I agree with ^^ – Padraic Cunningham Jun 19 '15 at 20:03
  • It's `__builtins__`, which happens to refer to a module named `__builtin__`. It's very confusing. – RemcoGerlich Jun 19 '15 at 20:05
  • @MarkN, yep, use `__builtins__` as Remo suggests – Padraic Cunningham Jun 19 '15 at 20:07
  • `__builtins__` is available in both Python 2 and Python 3 without any imports. In Python 2, you can import the same with `import __builtin__`, and in Python 3 it is `import builtins`. – chepner Jun 19 '15 at 20:08
  • For reference about the two and their differences: http://stackoverflow.com/questions/11181519/python-whats-the-difference-between-builtin-and-builtins – Mark N Jun 19 '15 at 20:09