¿Por qué “ejemplo = lista (…)” da como resultado “Error de tipo: el objeto ‘lista’ no se puede llamar”? [duplicate]

11 minutos de lectura

avatar de usuario de khan shah
khan shah

Traté de usar este código de un tutorial en el REPL:

example = list('easyhoss')

El tutorial dice que example debe volverse igual a una lista ['e', 'a', 's', 'y', 'h', 'o', 's', 's']. Pero recibí un error en su lugar:

>>> example = list('easyhoss')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable

¿Por qué pasó esto?

  • En algún lugar que hayas asignado una instancia de lista real al nombre listsombreando el incorporado; no hagas eso!

    – jonrsharpe

    27 de junio de 2015 a las 9:18


  • Intentar print(list) y mira lo que obtienes.

    usuario707650

    27 de junio de 2015 a las 9:21

  • @khanshah, ya sea que lo recuerde o no, eso es lo que le dice el mensaje de error. buscar por ejemplo lista = [... and get rid of it.

    – jonrsharpe

    Jun 27, 2015 at 9:21


Eli Korvigo's user avatar
Eli Korvigo

Seems like you’ve shadowed the builtin name list, which points at a class, by the same name pointing at an instance of it. Here is an example:

>>> example = list('easyhoss')  # here `list` refers to the builtin class
>>> list = list('abc')  # we create a variable `list` referencing an instance of `list`
>>> example = list('easyhoss')  # here `list` refers to the instance
Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: 'list' object is not callable

I believe this is fairly obvious. Python stores object names (functions and classes are objects, too) in namespaces (which are implemented as dictionaries), hence you can rewrite pretty much any name in any scope. It won’t show up as an error of some sort. As you might know, Python emphasizes that “special cases aren’t special enough to break the rules”. And there are two major rules behind the problem you’ve faced:

  1. Namespaces. Python supports nested namespaces. Theoretically you can endlessly nest them. As I’ve already mentioned, they are basically dictionaries of names and references to corresponding objects. Any module you create gets its own “global” namespace, though in fact it’s just a local namespace with respect to that particular module.

  2. Scoping. When you reference a name, the Python runtime looks it up in the local namespace (with respect to the reference) and, if such name does not exist, it repeats the attempt in a higher-level namespace. This process continues until there are no higher namespaces left. In that case you get a NameError. Builtin functions and classes reside in a special high-order namespace __builtins__. If you declare a variable named list in your module’s global namespace, the interpreter will never search for that name in a higher-level namespace (that is __builtins__). Similarly, suppose you create a variable var inside a function in your module, and another variable var in the module. Then, if you reference var inside the function, you will never get the global var, because there is a var in the local namespace – the interpreter has no need to search it elsewhere.

Here is a simple illustration.

>>> example = list("abc")  # Works fine
>>> 
>>> # Creating name "list" in the global namespace of the module
>>> list = list("abc")
>>> 
>>> example = list("abc")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
>>> # Python looks for "list" and finds it in the global namespace,
>>> # but it's not the proper "list".
>>> 
>>> # Let's remove "list" from the global namespace
>>> del list
>>> # Since there is no "list" in the global namespace of the module,
>>> # Python goes to a higher-level namespace to find the name. 
>>> example = list("abc")  # It works.

So, as you see there is nothing special about Python builtins. And your case is a mere example of universal rules. You’d better use an IDE (e.g. a free version of PyCharm, or Atom with Python plugins) that highlights name shadowing to avoid such errors.

You might as well be wondering what is a “callable”, in which case you can read this post. list, being a class, is callable. Calling a class triggers instance construction and initialisation. An instance might as well be callable, but list instances are not. If you are even more puzzled by the distinction between classes and instances, then you might want to read the documentation (quite conveniently, the same page covers namespaces and scoping).

If you want to know more about builtins, please read the answer by Christian Dean.

P.S. When you start an interactive Python session, you create a temporary module.

  • So, what does it do? List is built in. It should work fine.

    – khan shah

    Jun 27, 2015 at 9:24

  • @khanshah Python is very flexible: you can reassign builtins to something else, like here.

    – user707650

    Jun 27, 2015 at 9:25

  • You can always retrieve the original built-in with __builtins__.list.

    – user707650

    Jun 27, 2015 at 9:27

Christian Dean's user avatar
Christian Dean

Before you can fully understand what the error means and how to solve, it is important to understand what a built-in name is in Python.

What is a built-in name?

In Python, a built-in name is a name that the Python interpreter already has assigned a predefined value. The value can be either a function or class object. These names are always made available by default, no matter the scope. Some of the values assigned to these names represent fundamental types of the Python language, while others are simple useful.

As of the latest version of Python – 3.6.2 – there are currently 61 built-in names. A full list of the names and how they should be used, can be found in the documentation section Built-in Functions.

An important point to note however, is that Python will not stop you from re-assigning builtin names. Built-in names are not reserved, and Python allows them to be used as variable names as well.

Here is an example using the dict built-in:

>>> dict = {}
>>> dict
{}
>>>

As you can see, Python allowed us to assign the dict name, to reference a dictionary object.

What does “TypeError: ‘list’ object is not callable” mean?

To put it simply, the reason the error is occurring is because you re-assigned the builtin name list in the script:

list = [1, 2, 3, 4, 5]

Cuando hiciste esto, sobrescribió el valor predefinido del nombre incorporado. Esto significa que ya no puede usar el valor predefinido de listque es un objeto de clase que representa la lista de Python.

Por lo tanto, cuando intentaste usar el list clase para crear una nueva lista a partir de una range objeto:

myrange = list(range(1, 10))

Python generó un error. La razón por la que el error dice “el objeto ‘lista’ no se puede llamar”, es porque, como se dijo anteriormente, el nombre list se refería a un objeto de lista. Así que lo anterior sería el equivalente a hacer:

[1, 2, 3, 4, 5](range(1, 10))

Lo cual, por supuesto, no tiene sentido. No puede llamar a un objeto de lista.

¿Cómo puedo corregir el error?

Supongamos que tiene un código como el siguiente:

list = [1, 2, 3, 4, 5]
myrange = list(range(1, 10))

for number in list:
    if number in myrange:
        print(number, 'is between 1 and 10')

Ejecutar el código anterior produce el siguiente error:

Traceback (most recent call last):
  File "python", line 2, in <module>
TypeError: 'list' object is not callable

Si obtiene un error similar, como el anterior, que dice que “el objeto no se puede llamar”, es probable que haya utilizado un nombre incorporado como variable en su código. En este y otros casos, la solución es tan simple como cambiar el nombre de la variable infractora. Por ejemplo, para corregir el código anterior, podríamos cambiar el nombre de nuestro list variable a ints:

ints = [1, 2, 3, 4, 5] # Rename "list" to "ints"
myrange = list(range(1, 10))

for number in ints: # Renamed "list" to "ints"
    if number in myrange:
        print(number, 'is between 1 and 10')

PEP8 – la guía de estilo oficial de Python – incluye muchas recomendaciones sobre cómo nombrar variables.

Este es un error muy común que cometen los usuarios nuevos y antiguos de Python. Por eso es importante evitar siempre el uso de nombres incorporados como variables como str, dict, list, rangeetc.

Muchos linters e IDE le avisarán cuando intente utilizar un nombre integrado como variable. Si comete este error con frecuencia, puede valer la pena invertir su tiempo en uno de estos programas.

No cambié el nombre de un nombre incorporado, pero sigo recibiendo “Error de tipo: el objeto ‘lista’ no se puede llamar”. ¿Lo que da?

Otra causa común del error anterior es intentar indexar una lista usando paréntesis (()) en lugar de corchetes ([]). Por ejemplo:

>>> lst = [1, 2]
>>> lst(0)

Traceback (most recent call last):
  File "<pyshell#32>", line 1, in <module>
    lst(0)
TypeError: 'list' object is not callable

Para obtener una explicación del problema completo y qué se puede hacer para solucionarlo, consulte TypeError: el objeto ‘list’ no se puede llamar al intentar acceder a una lista.

Si está en una sesión interactiva y no desea reiniciar, puede eliminar el sombreado con

del list

En la liga de errores estúpidos de los lunes por la mañana, usar corchetes en lugar de corchetes al intentar acceder a un elemento de la lista también le dará el mismo mensaje de error:

l=[1,2,3]

print(l[2])#GOOD
print(l(2))#BAD

TypeError: el objeto ‘lista’ no se puede llamar

Avatar de usuario de Kevin
Kevin

Es posible que haya utilizado el nombre integrado ‘lista’ para una variable en su código. Si está utilizando el cuaderno Jupyter, a veces incluso si cambia el nombre de esa variable de ‘lista’ a algo diferente y vuelve a ejecutar esa celda, aún puede obtener el error. En este caso, debe reiniciar Kernal. Para asegurarse de que el nombre ha cambiado, haga clic en la palabra ‘lista’ cuando esté creando un objeto de lista y presione Turno+Pestañay verifique si Docstring lo muestra como una lista vacía.

Nombre de lista incorporado usado para mi lista

Cambie el nombre de mi lista a my_list pero aún obtenga un error, Shift + Tab muestra que la lista aún contiene los valores de my_list

Reinicie Kernal y todo está bien

Avatar de usuario de la comunidad
Comunidad

Por que TypeError: 'list' object is not callable ¿aparecer?

Explicación:

Es porque definiste list como una variable antes (estoy bastante seguro), por lo que sería una lista, ya no la función, es por eso que todos no deberían nombrar funciones de variables, lo siguiente es lo mismo que está haciendo ahora:

>>> [1,2,3]()
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    [1,2,3]()
TypeError: 'list' object is not callable
>>>  

Por lo tanto, necesita que sea la función predeterminada de list, ¿cómo detectar si lo es? Solo usa:

>>> list
<class 'list'>
>>> list = [1,2,3]
>>> list
[1, 2, 3]
>>> list()
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    list()
TypeError: 'list' object is not callable
>>> 

¿Cómo detecto si un nombre de variable es una función? bueno, solo mira si tiene un color diferente, o usa un código como:

>>> 'list' in dir(__builtins__)
True
>>> 'blah' in dir(__builtins__)
False
>>> 

Después de esto, debes saber por qué TypeError: 'list' object is not callable aparecer.

Bien, entonces ahora…

Cómo arreglar esto TypeError: 'list' object is not callable ¿error?

Código:

Tienes que hacer __builtins__.list():

>>> list = [1,2,3]
>>> __builtins__.list()
[]
>>> 

O usar []:

>>> list = [1,2,3]
>>> []
[]
>>> 

o eliminar list variable de memoria:

>>> list = [1,2,3]
>>> del list
>>> list()
[]
>>> 

O simplemente cambie el nombre de la variable:

>>> lst = [1,2,3]
>>> list()
[]
>>> 

PD El último es el más preferible, supongo 🙂

Hay un montón de soluciones que funcionan.

Referencias:

‘id’ es un nombre de variable incorrecto en Python

¿Cómo utilizo una palabra clave como nombre de variable?

¿Cómo usar la palabra clave reservada como nombre de variable en python?

Avatar de usuario de George
Jorge

descubra lo que ha asignado a ‘lista’ mostrándolo

>>> print(list)

si tiene contenido hay que limpiarlo con

>>> del list

ahora muestre ‘lista’ nuevamente y espere esto

<class 'list'>

Una vez que vea esto, puede continuar con su copia.

¿Ha sido útil esta solución?