Bool object is not callable ошибка

The TypeError ‘bool’ object is not callable occurs when you try to call a Boolean by putting parenthesis () after it like a function. Only functions respond to function calls.

This tutorial will go through the error in detail and how to solve it with the help of code examples.


Table of contents

  • TypeError: ‘bool’ object is not callable
  • Example
    • Solution
  • Summary

TypeError: ‘bool’ object is not callable

Calling a function means the Python interpreter executes the code inside the function. In Python, we can only call functions. We can call functions by specifying the name of the function we want to use followed by a set of parentheses, for example, function_name(). Let’s look at an example of a working function that returns a string.

# Declare function

def simple_function():

    print("Learning Python is fun!")

# Call function

simple_function()
Learning Python is fun!

We declare a function called simple_function in the code, which prints a string. We can then call the function, and the Python interpreter executes the code inside simple_function().

Bool type objects do not respond to a function call because they are not functions. If you try to call a Bool type object if it were a function, the Python interpreter will raise the TypeError: ‘bool’ object is not callable.

We can verify if an object is callable by using the built-in callable() method and passing the object to it. If the method returns True, then the object is callable, otherwise, if it returns False the object is not callable. Let’s look at testing the method with a Boolean:

a_bool = True

print(callable(a_bool))
False

The callable function returns false for a Boolean, verifying that bool objects are not callable.

Example

Let’s look at an example where we define a function that checks if a number is a prime number. We will use this function to check if a list of numbers contains prime numbers. First, let’s look at the function, which we will call prime_number.

def prime_number(num):

    # Is prime number flag

    is_prime = False

    # Prime numbers are greater than 1

    if num > 1:

        # Check for factors

        for i in range(2, num):

            #If factor is found, set is_prime to True

            if (num % i) == 0:

                is_prime = True

                # break out of the loop

                break

    return is_prime

The function takes in one argument, which is the number we want to check, and returns True if the number is prime and False if it is not. Next, we will iterate over a list of numbers and pass each number to a prime_number function call.

lst = [4, 7, 12, 17, 23, 44]

for i in lst:

    prime_number = prime_number(i)

    print(f'Is {i} Prime? {prime_number}')

Let’s run the code to see what happens:

Is 4 Prime? False
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-10-cb5177ccdebb> in <module>
      2 
      3 for i in lst:
----> 4     prime_number = prime_number(i)
      5     print(f'Is {i} Prime? {prime_number}')

TypeError: 'bool' object is not callable

We get a TypeError because the variable prime_number has the same name as the function we want to call. The variable gets assigned a Boolean value for the first loop.

Because the variable has the same name as the function, the Boolean value overrides the function.

Then, in the second loop, when we try to call the prime_number() function we are calling the Boolean value from the previous loop instead.

We can verify the override by checking the type of prime_number using type().

lst = [4, 7, 12, 17, 23, 44]

for i in lst:

    print(type(prime_number))

    prime_number = prime_number(i)

    print(type(prime_number))

    print(f'Is {i} Prime? {prime_number}')
<class 'function'>
<class 'bool'>
Is 4 Prime? True
<class 'bool'>

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-7-5ba50fe7142f> in <module>
      3 for i in lst:
      4     print(type(prime_number))
----> 5     prime_number = prime_number(i)
      6     print(type(prime_number))
      7     print(f'Is {i} Prime? {prime_number}')

TypeError: 'bool' object is not callable

We see that at the start of the loop, prime_number is a function, and then after the first call prime_number is Boolean. Then at the start of the second loop, when we want to make a function call, prime_number is still a Boolean.

Solution

To solve this error, we need to use a distinct variable name. We will choose is_prime instead of prime_number. If you are using IPython, ensure you start from a new session or redefine the prime_number function. Let’s look at the revised code:

lst = [4, 7, 12, 17, 23, 44]

for i in lst:

    is_prime = prime_number(i)

    print(f'Is {i} Prime? {is_prime}')

Let’s run the code to see the result:

Is 4 Prime? True
Is 7 Prime? False
Is 12 Prime? True
Is 17 Prime? False
Is 23 Prime? False
Is 44 Prime? True

We can also verify that prime_number stays as a function during the entire program lifecycle:

lst = [4, 7, 12, 17, 23, 44]

for i in lst:

    print(type(prime_number))

    is_prime = prime_number(i)

    print(type(prime_number))

    print(f'Is {i} Prime? {is_prime}')

Let’s run the code to see the result:

<class 'function'>
<class 'function'>
Is 4 Prime? True
<class 'function'>
<class 'function'>
Is 7 Prime? False
<class 'function'>
<class 'function'>
Is 12 Prime? True
<class 'function'>
<class 'function'>
Is 17 Prime? False
<class 'function'>
<class 'function'>
Is 23 Prime? False
<class 'function'>
<class 'function'>
Is 44 Prime? True

Summary

Congratulations on reading to the end of this tutorial. The TypeError ‘bool’ object is not callable occurs when you try to call a Boolean as if it were a function. TypeErrors occur when you attempt to perform an illegal operation for a specific data type.

To solve this error, ensure that the variable names and function names are distinct and that there are no parentheses after Boolean values. You can check if an object is a Boolean by using the built-in type() method.

For further reading on not callable TypeErrors, go to the articles:

  • How to Solve Python TypeError: ‘tuple’ object is not callable.
  • How to Solve Python TypeError: ‘DataFrame’ object is not callable.

To learn more about Python, specifically for data science and machine learning, go to the online courses page on Python.

Have fun and happy researching!

I am brand new to python. I got a error

while not cls.isFilled(row,col,myMap):
TypeError: 'bool' object is not callable

Would you please instruct how to solve this issue?
The first «if» check is fine, but «while not» has this error.

def main(cls, args):
        ...
        if cls.isFilled(row,col,myMap):
            numCycles = 0

        while not cls.isFilled(row,col,myMap):
            numCycles += 1


def isFilled(cls,row,col,myMap):
        cls.isFilled = True
        ## for-while
        i = 0
        while i < row:
            ## for-while
            j = 0
            while j < col:
                if not myMap[i][j].getIsActive():
                    cls.isFilled = False
                j += 1
            i += 1
        return cls.isFilled

Cover image for How to fix "‘bool’ object is not callable" in Python

Update: This post was originally published on my blog decodingweb.dev, where you can read the latest version for a 💯 user experience. ~reza

The “TypeError: ‘bool’ object is not callable” error occurs when you try to call a boolean value (bool object) as if it was a function!

Here’s what the error looks like:

Traceback (most recent call last):
  File /dwd/sandbox/test.py, line 3, in <module>
    if is_active() == true:
       ^^^^^^^^^^^
TypeError: 'bool' object is not callable

Enter fullscreen mode

Exit fullscreen mode

In the simplest terms, this is what happens:

is_active = True

# ⚠️ is_active is a boolean value not a callable
if is_active() == True:
    print('User is active.')

Enter fullscreen mode

Exit fullscreen mode

Calling a boolean value like a callable isn’t what you’d do on purpose, though. It usually happens due to unwanted value assignments. Or accidentally overriding a function’s global name with True or False!

To fix the issue, trace the error back up to the statement that changed your function to a boolean value.

Additionally, if you accidentally put an extra parenthesis after a built-in or user-defined function that returns a boolean value, you’ll get the error:

# 🚫 Raises TypeError: 'bool' object is not callable
bool()()

Enter fullscreen mode

Exit fullscreen mode

In the above example, bool() returns False, and having an extra pair of parenthesis is like False().

How to fix TypeError: ‘bool’ object is not callable?

First, inspect the respective function’s value, and figure out how it ended up being a boolean object in the first place.

Sometimes figuring this out might be tricky. Below are three scenarios that lead to the «TypeError: ‘bool’ object is not callable» error:

  1. Declaring variable with a name that’s also the name of a function
  2. Calling a method that’s also the name of a property
  3. Calling a method decorated with @property

Let’s explore each scenario with some examples.

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 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, str() is __builtins__.str().

That said, overriding a function (accidentally or on purpose) with another value is technically possible.

For instance, if you define a variable named str and initialize it with a boolean value, it’ll no longer point to the str class.

# ⚠️ the value of the built-in function str() is changed to True
str = True
score = 15

# 🚫 Raises TypeError
print ('The score is: ' + str(score))

Enter fullscreen mode

Exit fullscreen mode

If you run the above code, Python will complain with a «TypeError: ‘bool’ object is not callable» error because True (the new value of str) isn’t callable.

You have two ways to fix the issue:

  • Rename the variable str
  • Explicitly access the str function from the builtins module (__bultins__.str)

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)
     # ...

Enter fullscreen mode

Exit fullscreen mode

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:

status = True
score = 15

print ('The score is: ' + str(score))
# Output: The score is: 15

Enter fullscreen mode

Exit fullscreen mode

⚠️ 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 one of the most common causes of the «TypeError: ‘bool’ object is not callable» error. It’s similar to calling integer numbers.

Now, let’s get to the less common mistakes that lead to this error.

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, published):
        self.title = title
        self.published = published

    def published(self):
        return self.published


book = Book('Learning Python', True)

# 🚫 Raises TypeError: 'bool' object is not callable
if book.published():
    print('The book is published.')

Enter fullscreen mode

Exit fullscreen mode

In the above code, class Book contains a property named published that defines whether the books is published or not. Further down, we defined a method, also named published.

As a result, any reference to published returns the property not the method. And if you try to call this property, you should expect the «TypeError: ‘bool’ object is not callable» error.

The method name is_published sounds like a safer and more readable alternative:

class Book:
    def __init__(self, title, published):
        self.title = title
        self.published = published

    def is_published(self):
        return self.published


book = Book('Learning Python', True)

if book.is_published():
    print('The book is published.')
# Output: The book is published.

Enter fullscreen mode

Exit fullscreen mode

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.

class User:
    def __init__(self, user_id, active):
        self._user_id = user_id
        self._active = active

    @property
    def active(self):
        return self._active


user = User(1, True)

# 🚫 Raises TypeError: 'bool' object is not callable
if user.active():
    print('User is active!')

Enter fullscreen mode

Exit fullscreen mode

You need to access the getter method without the parentheses:

class User:
    def __init__(self, user_id, active):
        self._user_id = user_id
        self._active = active

    @property
    def active(self):
        return self._active


user = User(1, True)

if user.active:
    print('User is active!')

# Output: User is active!

Enter fullscreen mode

Exit fullscreen mode

Problem solved!

Alright, I think it does it! I hope this quick guide helped you fix your problem.

Thanks for reading.

❤️ You might like:

  • TypeError: ‘tuple’ object is not callable in Python
  • TypeError: ‘dict’ object is not callable in Python
  • TypeError: ‘list’ object is not callable in Python
  • TypeError: ‘str’ object is not callable in Python
  • TypeError: ‘float’ object is not callable» in Python
  • TypeError: ‘int’ object is not callable in Python

TypeError: ‘bool’ object is not callable in Python; it could be that you are naming the function the same as the variable that contains the data type, or maybe you are overriding the bool() function to a primitive function containing the boolean data type then calling it out. Follow this article to understand better.

The reason is that bool objects do not respond to function calls because they are not functions.

Example: 

def checkEvenNumber(num):
  if (num % 2) == 0:
    return True
  else:
    return False  

checkEvenNumber = True
checkEvenNumber = checkEvenNumber(3) # TypeError: 'bool' object is not callable
print(checkEvenNumber)

Output:

TypeError: 'bool' object is not callable

The cause of the error was that I declared a variable named with the function we want to call: checkEvenNumber = checkEvenNumber(3)

How to solve this error?

The difference in variable and function naming

To fix this, you need to be careful not to name the function the same as the variable name containing the boolean data type.

Example:

  • Use a different variable name than the function name.
  • I replaced the variable name ‘isEvenNumber’ in the wrong statement checkEvenNumber = checkEvenNumber(3) to isEvenNumber = checkEvenNumber(3).
def checkEvenNumber(num):
  if (num % 2) == 0:
    return True
  else:
    return False  

isEvenNumber = True
isEvenNumber = checkEvenNumber(3)
print(isEvenNumber)

Output:

False

Overriding built-in functions in Python

Example:

bool = False
print(bool('learnshareit'))

Output:

Traceback (most recent call last):
  File "code.py", line 2, in <module>
    print(bool('learnshareit'))
TypeError: 'bool' object is not callable

In this case, the mistake that caused the error was to override the list() function to a primitive function containing the boolean data type and then call it.

To fix the error in the above value, you need to change the variable that contains a boolean data type that is not the name of a built-in function in Python.

Example:

# Change the variable name. Avoid naming variables as built-in functions in Python
boolObj = False
print(bool('learnshareit'))

Output:

True

Checking if an object is callable

This is not a fix but a way for you to check if an object is callable to avoid mishaps while you code. I will use the callable() function.

Syntax:

callable(object)

Parameters:

  • object: object to be tested.

The callable() function checks if the objects are callable or not. If the object is allowed to be called, the function returns True. Otherwise, it returns False.

Example:

bool = False
print(callable(bool))

Output:

False

In the above example, the callable() function returns False, which ensures that the bool object is not callable.

Summary

I hope you enjoy our article about the TypeError: ‘bool’ object is not callable in Python. If you have any questions about this issue, please leave a comment below. We will answer your questions as possible. Thanks!

Maybe you are interested:

  • SyntaxError: non-default argument follows default argument
  • TypeError: ‘tuple’ object does not support item assignment
  • TypeError: can only concatenate str (not “list”) to str

Jason Wilson

My name is Jason Wilson, you can call me Jason. My major is information technology, and I am proficient in C++, Python, and Java. I hope my writings are useful to you while you study programming languages.


Name of the university: HHAU
Major: IT
Programming Languages: C++, Python, Java

I’m trying to implement a simple maths game where the user is given random numbers and operators then they have to work out the answer, I found sources on the internet that suggested using the operator module, which is why i used it, if there is a more efficient/ easier way of achieving this I am very open for interpretation.

Essentially i am trying to remove this horrible <built-in function add> and swap it to be more user friendly by saying ‘+’ or ‘add’, something along those lines but i keep getting the error ‘TypeError: ‘bool’ object is not callable — python’, i really dont know what this means, i am new to python and am very confused.

 from operator import add, sub, mul, floordiv

 operators = (add == str("add"), sub == str("subtract"), mul == str("multiply"), floordiv == str("divide"))
 operator = random.choice(operators)
 answer = operator(number1, number2)
 question = print("What is ", number1, operator, number2, "?")

favoretti's user avatar

favoretti

29.1k4 gold badges47 silver badges61 bronze badges

asked Nov 25, 2014 at 13:45

Josh Hughes's user avatar

6

You want two seperate things: the string representation of the operator and the operator itself. You can use dictionary to store the function and the corresponding string representation:

from operator import add, sub, mul, floordiv
import random

number1 = 9
number2 = 3

operators = {'+':add, '-':sub, '*':mul, '/':floordiv}
operator_name = random.choice(operators.keys())
op = operators[operator_name]
answer = op(number1, number2)
question = "What is {}{}{}?".format(number1, operator_name, number2)
print question
print answer

answered Nov 25, 2014 at 13:55

hitzg's user avatar

hitzghitzg

12.1k52 silver badges54 bronze badges

What you get as a result of the first line is

operators = (False, False, False, False, False)

or something in those lines.

Then you are trying to call a boolean that gets you the exception you have.

add == str("add") will evaluate to False, since you’re trying to compare a function to a string.

I’m assuming you are trying to implement a simple math game, hence instead of using operator, which are in fact math operation functions, you can just use a simple dictonary:

operators = { 'add': add, 'substract': sub, 'multiply': mul }
answer = operators[random.choice(operators.keys())](number1, number2)

answered Nov 25, 2014 at 13:47

favoretti's user avatar

favorettifavoretti

29.1k4 gold badges47 silver badges61 bronze badges

2

Here’s an implementation using tuples instead of dicts, I added in more ways to represent each operation.

import random
from operator import add, sub, mul, floordiv

number1 = 5
number2 = 10

operators = (
    (add, ("add", "plus", "+")),
    (sub, ("subtract", "minus", "-")),
    (mul, ("multiply", "times", "*")),
    (floordiv, ("divide", "over", "/")),
)
operator, (name, operation, symbol) = random.choice(operators)
print("What is ", number1, operation, number2, "?")
print(operator(number1, number2))

Output

13:50 ~ $ python3 StackOverflow/27128400.py 
What is  5 times 10 ?
50
13:55 ~ $ python3 StackOverflow/27128400.py 
What is  5 plus 10 ?
15
13:55 ~ $ python3 StackOverflow/27128400.py 
What is  5 minus 10 ?
-5
13:55 ~ $ python3 StackOverflow/27128400.py 
What is  5 over 10 ?
0

answered Nov 25, 2014 at 13:59

Ngenator's user avatar

NgenatorNgenator

10.9k4 gold badges41 silver badges46 bronze badges

0

What you’re trying to do here is certainly possible. The formation of the tuple above does not return anything useful. A dictionary is more appropriate.

You can construct the dictionary as:

operators = {'add':add, 'minus':sub, 'multiplied by':mul, 'divided by':floordiv}

This gives you a dictionary of related strings and functions. You can choose a random operator name (this will give the string value, not the operator itself.

operator = random.choice(list(operators.keys()))

Then compute the answer:

answer = operators.get(operator)(number1, number2)

This gets the operator function from the operators dictionary by ‘searching’ for its string partner.

Altogether now (with some numbers so it runs off the bat):

from operator import add, sub, mul, floordiv
import random 

operators = {'add':add, 'minus':sub, 'multiplied by':mul, 'divided by':floordiv}
operator = random.choice(list(operators.keys()))
number1 = 2
number2 = 3
answer = operators.get(operator)(number1, number2)
print "What is " + str(number1) + " " + operator + " " + str(number2) + "?"
print answer

(I’m using 2.7 for this)

answered Nov 25, 2014 at 14:10

JBux's user avatar

JBuxJBux

1,3968 silver badges17 bronze badges

2

Возможно, вам также будет интересно:

  • Boneco h680 ошибка е3 что делать
  • Boneco 680 ошибка e3
  • Bolid ошибка параметров шс
  • Boi код ошибки 1
  • Body computer warning 43 iveco stralis ошибка

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии