- How to fix «‘list’ object is not callable» in Python
- How to fix TypeError: ‘list’ object is not callable?
- Решение ошибки TypeError: ‘module’ object is not callable в Python
- TypeError: module object is not callable [Python Error Solved]
- What Is a Module in Programming?
- What Does callable Mean in the “TypeError: module object is not callable” Error?
- What Does the “TypeError: module object is not callable” Error Mean in Python?
- How to Fix the “TypeError: module object is not callable” Error in Python
- Error Example #1
- Error Example #2
- Summary
How to fix «‘list’ object is not callable» in Python
Calling a list object as if it’s a callable isn’t what you’d do on purpose, though. It usually happens due to a wrong syntax or overriding a function name with a list object. Let’s explore the common causes and their solutions.
How to fix TypeError: ‘list’ object is not callable?
- Declaring a variable with a name that’s also the name of a function
- Indexing a list by parenthesis rather than square brackets
- Calling a method that’s also the name of a property
- Calling a method decorated with @property
Declaring a variable with a name that’s also the name of a function: A Python function is an object like any other built-in object, such as str , int , float , dict , list , etc.
All built-in functions are defined in the builtins module and assigned a global name for easier access. For instance, list refers to the __builtins__.list function.
That said, overriding a function (accidentally or on purpose) with any value (e.g., a list object) is technically possible.
In the following example, we’ve declared a variable named list containing a list of numbers. In its following line, we try to create another list — this time by using the list() and range() functions:
list = [1, 2, 3, 4, 5, 6, 8, 9, 10] # ⚠️ list is no longer pointing to the list function # Next, we try to generate a sequence to add to the current list more_items = list(range(11, 20)) # 👆 ⛔ Raises: TypeError: ‘list’ object is not callable
If you run the above code, Python will complain with a «TypeError: ‘list’ object is not callable» error because we’ve already assigned the list name to the first list object.
We have two ways to fix the issue:
- Rename the variable list
- Explicitly access the list() function from the builtins module ( __bultins__.list )
The second approach isn’t recommended unless you’re developing a module. For instance, if you want to implement an open() function that wraps the built-in open() :
# Custom open() function using the built-in open() internally def open(filename): # . __builtins__.open(filename, 'w', opener=opener) # .
In almost every other case, you should always avoid naming your variables as existing functions and methods. But if you’ve done so, renaming the variable would solve the issue.
So the above example could be fixed like this:
items = [1, 2, 3, 4, 5, 6, 8, 9, 10] # Next, we try to generate a sequence to add to the current list more_items = list(range(11, 20))
This issue is common with function names you’re more likely to use as variable names. Functions such as vars , locals , list , all , or even user-defined functions.
In the following example, we declare a variable named all containing a list of items. At some point, we call all() to check if all the elements in the list (also named all ) are True :
all = [1, 3, 4, True, 'hey there', 1] # ⚠️ all is no longer pointing to the built-in function all() # Checking if every element in all is True: print(all(all)) # 👆 ⛔ Raises TypeError: 'list' object is not callable
Obviously, we get the TypeError because the built-in function all() is now shadowed by the new value of the all variable.
To fix the issue, we choose a different name for our variable:
items = [1, 3, 4, True, 'hey there', 1] # Checking if every element in all is True: print(all(items)) # Output: True
⚠️ Long story short, you should never use a function name (built-in or user-defined) for your variables!
Overriding functions (and calling them later on) is the most common cause of the «TypeError: ‘list’ object is not callable» error. It’s similar to calling integer numbers as if they’re callables.
Now, let’s get to the less common mistakes that lead to this error.
Indexing a list by parenthesis rather than square brackets: Another common mistake is when you index a list by () instead of [] . Based on Python semantics, the interpreter will see any identifier followed by a () as a function call. And since the parenthesis follows a list object, it’s like you’re trying to call a list.
As a result, you’ll get the «TypeError: ‘list’ object is not callable» error.
items = [1, 2, 3, 4, 5, 6] print(items(2)) # 👆 ⛔ Raises TypeError: 'list' object is not callable
This is how you’re supposed to access a list item:
items = [1, 2, 3, 4, 5, 6] print(items[2]) # Output: 3
Calling a method that’s also the name of a property: When you define a property in a class constructor, it’ll shadow any other attribute of the same name.
class Book: def __init__(self, title, authors): self.title = title self.authors = authors def authors(self): return self.authors book = Book('The Pragmatic Programmer', ['David Thomas', 'Andrew Hunt']) print(book.authors()) # 👆 ⛔ Raises TypeError: 'list' object is not callable
In the above example, since we have a property named authors , the method authors() is shadowed. As a result, any reference to authors will return the property authors , returning a list object. And if you call this list object value like a function, you’ll get the «TypeError: ‘list’ object is not callable» error.
The name get_authors sounds like a safer and more readable alternative:
class Book: def __init__(self, title, authors): self.title = title self.authors = authors def get_authors(self): return self.authors book = Book('The Pragmatic Programmer', ['David Thomas', 'Andrew Hunt']) print(book.get_authors()) # Output: ['David Thomas', 'Andrew Hunt']
Calling a method decorated with @property decorator: The @property decorator turns a method into a “getter” for a read-only attribute of the same name. You need to access a getter method without parenthesis, otherwise you’ll get a TypeError.
class Book: def __init__(self, title, authors): self._title = title self._authors = authors @property def authors(self): """Get the authors' names""" return self._authors book = Book('The Pragmatic Programmer', ['David Thomas', 'Andrew Hunt']) print(book.authors()) # 👆 ⛔ Raises TypeError: 'list' object is not callable
To fix it, you need to access the getter method without the parentheses:
book = Book('The Pragmatic Programmer', ['David Thomas', 'Andrew Hunt']) print(book.authors) # Output: ['David Thomas', 'Andrew Hunt']
Alright, I think it does it! I hope this quick guide helped you fix your problem.
❤️ You might like:
Решение ошибки TypeError: ‘module’ object is not callable в Python
В процессе работы с Python иногда возникает ошибка «TypeError: ‘module’ object is not callable». Эта ошибка обычно происходит, когда разработчик пытается вызвать модуль, как функцию.
Пример ошибки:
import math result = math(5)
В этом коде разработчик пытается вызвать модуль math как функцию, что невозможно и вызывает ошибку TypeError: ‘module’ object is not callable .
Причина ошибки:
Модули в Python — это файлы, содержащие Python код, которые можно импортировать в другие Python файлы. Они не являются функциями и не могут быть вызваны как функции. Вместо этого, модули предоставляют функции, переменные и классы, которые можно использовать в другом коде после импорта модуля.
Решение ошибки:
Для решения этой ошибки необходимо вызвать функцию, класс или переменную из модуля, а не сам модуль. В приведенном выше примере, если был импортирован модуль math , следует вызвать функцию из этого модуля, а не сам модуль.
Исправленный пример:
import math result = math.sqrt(5)
В этом коде вызывается функция sqrt() из модуля math , а не сам модуль math . Этот код не вызовет ошибку TypeError: ‘module’ object is not callable , так как вызывается функция, а не модуль.
В заключение, ошибка «TypeError: ‘module’ object is not callable» в Python обычно указывает на то, что разработчик пытается вызвать модуль, как функцию. Для решения этой ошибки необходимо вызвать функцию, класс или переменную из модуля, а не сам модуль.
TypeError: module object is not callable [Python Error Solved]
Ihechikara Vincent Abba
In this article, we’ll talk about the «TypeError: ‘module’ object is not callable» error in Python.
We’ll start by defining some of the keywords found in the error message — module and callable .
You’ll then see some examples that raise the error, and how to fix it.
Feel free to skip the next two sections if you already know what modules are, and what it means to call a function or method.
What Is a Module in Programming?
In modular programming, modules are simply files that contain similar functionalities required to perform a certain task.
Modules help us separate and group code based on functionality. For example, you could have a module called math-ops.py which will only include code related to mathematical operations.
This makes easier to read, reuse, and understand the code. To use a module in a different part of your code base, you’d have to import it to gain access to all the functionalities defined in the module.
In Python, there are many built-in modules like os , math , time , and so on.
Here’s an example that shows how to use the math module:
import math print(math.sqrt(25)) //5.0
As you can see above, the first thing we did before using the math module was to import it: import math .
We then made use of the module’s sqrt method which returns the square root of a number: math.sqrt(25) .
All it took us to get the square root of 25 was two lines of code. In reality, the math module alone has over 3500 lines of code.
This should help you understand what a module is and how it works. You can also create your own modules (we’ll do that later in this article).
What Does callable Mean in the “TypeError: module object is not callable” Error?
In Python and most programming languages, the verb «call» is associated with executing the code written in a function or method.
Other similar terms mostly used with the same action are «invoke» and «fire».
Here’s a Python function that prints «Smile!» to the console:
If you run the code above, nothing will be printed to the console because the function smile is yet to be called, invoked, or fired.
To execute the function, we have to write the function name followed by parenthesis. That is:
def smile(): print("Smile!") smile() # Smile!
Without the parenthesis, the function will not be executed.
Now you should understand what the term callable means in the error message: «TypeError: ‘module’ object is not callable».
What Does the “TypeError: module object is not callable” Error Mean in Python?
The last two sections helped us understand some of the keywords found in the «TypeError: ‘module’ object is not callable» error message.
To put it simply, the «TypeError: ‘module’ object is not callable» error means that modules cannot be called like functions or methods.
How to Fix the “TypeError: module object is not callable” Error in Python
There are generally two ways that the «TypeError: ‘module’ object is not callable» error can be raised: calling an inbuilt or third party module, and calling a module in place of a function.
Error Example #1
import math print(math(25)) # TypeError: 'module' object is not callable
In the example above, we called the math module (by using parenthesis () ) and passed 25 as a parameter hoping to perform a particular math operation: math(25) . But we got the error.
To fix this, we can make use of any math method provided by the math module. We’ll use the sqrt method:
import math print(math.sqrt(25)) # 5.0
Error Example #2
For this example, I’ll create a module for calculating two numbers:
The name of the module above is add which can be derived from the file name add.py.
Let’s import the add() function from the add module in another file:
# main.py import add add(2,3) # TypeError: 'module' object is not callable
You must be wondering why we’re getting the error even though we imported the module.
Well, we imported the module, not the function. That’s why.
To fix this, you have to specify the name of the function while importing the module:
from add import add add(2,3) # 5
We’re being specific: from add import add . This is the same as saying, «from the add.py module, import the add function».
You can now use the add() function in the main.py file.
Summary
In this article, we talked about the «TypeError: ‘module’ object is not callable» error in Python.
This error occurs mainly when we call or invoke a module as though it were a function or method.
We started by discussing what a module is in programming, and what it means to call a function – this helped us understand what causes the error.
We then gave some examples that showed the error being raised and how to fix it.