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?
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.
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'>
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