[docs] Python bug.

Zachary Ware zachary.ware+pydocs at gmail.com
Thu Nov 27 05:01:26 CET 2014


Hi Lusine,

First, I'd like to note that this is not the correct list for
reporting bugs with Python itself; this list is for discussion of
Python's documentation.  That being said...

On Wed, Nov 26, 2014 at 1:32 PM, Lusine Atanesyan <atlusine at gmail.com> wrote:
> Hi,
>
> I found a pyhton bug. Here is the description:
>
> Summary:
>       It is impossible to change tuple to list.
>
> Overview description.
>       It is impossible to change tuple to list when there is a independent
> list with the "list" name.
>
> Steps to reproduce:
>        >>> list = [1, 2, 3]
>        >>> tup = (5, 6, 7)
>        >>> list(tup)
>
> Actual result:
>       The following error is generated:
>            Traceback (most recent call last):
>            File "<stdin>", line 1, in <module>
>            TypeError: 'list' object is not callable

This is the expected result.  By using the name "list" for a list
object, you are shadowing the built-in name "list", which is the name
of the list object constructor.  Python's name resolution algorithm
first checks for a local name, followed by a global name if no local
is found, followed by a built-in name (a member of the builtins (or
__builtin__ in Python2) module).  Since executing "list = [1,2,3]"
creates a local name "list", it is found before the built-in name
"list"; list objects are not callable, hence the error you got.  Note
that it doesn't actually matter what you define the local name "list"
to be:

>>> list = "this is not a list"
>>> tup = (4,5,6)
>>> list(tup)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable

> Expect result:
>       Either it should be possible to change the tuple to list or the error
> should generated when creating a list with the "list" name.

Name shadowing can be a very useful feature, allowing things like (in
Python 3) redefining the name "print" to be a wrapper around
"log.debug", so it's not going away.  The real solution here is to
either just not use the name "list" in a local scope (a lot of people
use "lst" or "list_" or just "l" if your font distinguishes between
"l" and "I" properly), or to import builtins (or __builtin__ in Python
2) and use "builtins.list" instead of just "list" when you need the
built-in list.  It's also possible to do something extraordinarily
ugly like "type([])(tup)", but that's just going a little too far :)

Hope this helps,
-- 
Zach


More information about the docs mailing list