Home >Backend Development >Python Tutorial >Why does `example = list(...)` raise a `TypeError: 'list' object is not callable`?
In the REPL, you may encounter the error ""TypeError: 'list' object is not callable"" when attempting to assign a list to the variable example using the following code:
example = list('easyhoss')
This issue arises because the Python builtin name list, which refers to a class, has been shadowed by creating a variable with the same name. This variable points to an instance of the list class.
To illustrate this shadowing:
>>> example = list('easyhoss') # 'list' refers to the builtin class >>> list = list('abc') # Create a variable 'list' referencing an instance of 'list' >>> example = list('easyhoss') # 'list' now refers to the instance Traceback (most recent call last): File "<string>", line 1, in <module> TypeError: 'list' object is not callable
As Python references objects (functions and classes included) by name in namespaces, you can rewrite any name in any scope. The runtime searches for the name in the local namespace and, if it is not found, proceeds to higher-level namespaces. This process continues until the name is encountered or a NameError is raised.
Builtins, such as list, reside in the high-order namespace __builtins__. If the variable list is declared in the global namespace of a module, the interpreter will not search for it in __builtins__. Similarly, if a variable var is created within a function, and another var is defined in the global namespace, referencing var from the function will always refer to the local variable.
For example:
>>> example = list("abc") # Works fine >>> >>> # Creating variable "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 finds "list" in the global namespace, >>> # but it is not the desired "list". >>> >>> # Remove "list" from the global namespace >>> del list >>> # Since "list" is no longer in the global namespace, >>> # Python searches in a higher-level namespace. >>> example = list("abc") # Works now
Therefore, Python builtins follow the same rules as all other objects. Shadowing, illustrated in this case, can be avoided by using an IDE that highlights name shadowing issues.
Additionally, list being a class is callable. Calling a class triggers instance construction and initialization. While an instance can also be callable, list instances are not. Classes and instances are distinctly different concepts explained in the Python documentation.
The above is the detailed content of Why does `example = list(...)` raise a `TypeError: 'list' object is not callable`?. For more information, please follow other related articles on the PHP Chinese website!