Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Naming conflict with built-in function

I have made a mistake as below:

>>> list = ['a', 'b', 'c']

But now I want to use the built-in function list(). As you can see, there is a naming conflict between listname list and the built-in function list().

How can I use list as a built-in function not the variable without restarting the Python shell?

like image 387
holys Avatar asked May 13 '13 13:05

holys


2 Answers

Step one: rebind the list to a different name

lst = list

Step two: delete the list variable

del list

Step three: don't do it again


I prefer this over __builtins__.list simply because it saves the typing, and you aren't still left with a variable named list. However, it is always best to avoid the problem altogether. When writing production code, always remember not to have variables named the same as built in functions.

like image 80
Volatility Avatar answered Oct 03 '22 14:10

Volatility


Use __builtins__.list or __builtins__['__list__'] (depending on context), or simply delete list again (del list).

No imports needed:

>>> __builtins__.list
<type 'list'>

The presence of __builtins__ is a CPython implementation detail; in the __main__ module it is a module, everywhere else it is the module __dict__ dictionary. Jython, IronPython and PyPy may opt to not make this available at all. Use the __builtin__ module for those platforms, or for Python 3 compatible implementations, the builtins module:

>>> import __builtin__
>>> __builtin__.list
<type 'list'>
like image 24
Martijn Pieters Avatar answered Oct 03 '22 15:10

Martijn Pieters