Bool object is not callable ошибка

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

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!

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

Replace: This publish was initially revealed on my weblog decodingweb.dev, the place you’ll be able to learn the latest version for a 💯 person expertise. ~reza

The “TypeError: ‘bool’ object shouldn’t be callable” error happens whenever you attempt to name a boolean worth (bool object) as if it was a operate!

Right here’s what the error appears like:

Traceback (most up-to-date name final):
  File /dwd/sandbox/take a look at.py, line 3, in <module>
    if is_active() == true:
       ^^^^^^^^^^^
TypeError: 'bool' object shouldn't be callable
Enter fullscreen mode

Exit fullscreen mode

Within the easiest phrases, that is what occurs:

is_active = True

# ⚠️ is_active is a boolean worth not a callable
if is_active() == True:
    print('Person is energetic.')
Enter fullscreen mode

Exit fullscreen mode

Calling a boolean worth like a callable is not what you’d do on objective, although. It normally occurs resulting from undesirable worth assignments. Or by accident overriding a operate’s international identify with True or False!

To repair the problem, hint the error again as much as the assertion that modified your operate to a boolean worth.

Moreover, should you by accident put an additional parenthesis after a built-in or user-defined operate that returns a boolean worth, you will get the error:

# 🚫 Raises TypeError: 'bool' object shouldn't be callable
bool()()
Enter fullscreen mode

Exit fullscreen mode

Within the above instance, bool() returns False, and having an additional pair of parenthesis is like False().

The best way to repair TypeError: ‘bool’ object shouldn’t be callable?

First, examine the respective operate’s worth, and work out the way it ended up being a boolean object within the first place.

Typically figuring this out is likely to be difficult. Beneath are three eventualities that result in the “TypeError: ‘bool’ object shouldn’t be callable” error:

  1. Declaring variable with a reputation that is additionally the identify of a operate
  2. Calling a way that is additionally the identify of a property
  3. Calling a way embellished with @property

Let’s discover every situation with some examples.

Declaring a variable with a reputation that is additionally the identify of a operate: A Python operate is an object like some other built-in object, similar to int, float, dict, checklist, and so forth.

All built-in capabilities are outlined within the builtins module and assigned a worldwide identify for simpler entry. As an example, str() is __builtins__.str().

That mentioned, overriding a operate (by accident or on objective) with one other worth is technically potential.

As an example, should you outline a variable named str and initialize it with a boolean worth, it will not level to the str class.

# ⚠️ the worth of the built-in operate str() is modified to True
str = True
rating = 15

# 🚫 Raises TypeError
print ('The rating is: ' + str(rating))
Enter fullscreen mode

Exit fullscreen mode

In the event you run the above code, Python will complain with a “TypeError: ‘bool’ object shouldn’t be callable” error as a result of True (the brand new worth of str) is not callable.

You will have two methods to repair the problem:

  • Rename the variable str
  • Explicitly entry the str operate from the builtins module (__bultins__.str)

The second strategy is not advisable except you are growing a module. As an example, if you wish to implement an open() operate that wraps the built-in open():

# Customized open() operate utilizing the built-in open() internally
def open(filename):
     # ...
     __builtins__.open(filename, 'w', opener=opener)
     # ...
Enter fullscreen mode

Exit fullscreen mode

In nearly each different case, it’s best to all the time keep away from naming your variables as present capabilities and strategies. However should you’ve completed so, renaming the variable would clear up the problem.

So the above instance could possibly be fastened like this:

standing = True
rating = 15

print ('The rating is: ' + str(rating))
# Output: The rating is: 15
Enter fullscreen mode

Exit fullscreen mode

⚠️ Lengthy story brief, it’s best to by no means use a operate identify (built-in or user-defined) in your variables!

Overriding capabilities (and calling them in a while) is among the most typical causes of the “TypeError: ‘bool’ object shouldn’t be callable” error. It is much like calling integer numbers.

Now, let’s get to the much less frequent errors that result in this error.

Calling a way that is additionally the identify of a property: Once you outline a property in a category constructor, it will shadow some other attribute of the identical identify.

class E-book:
    def __init__(self, title, revealed):
        self.title = title
        self.revealed = revealed

    def revealed(self):
        return self.revealed


e book = E-book('Studying Python', True)

# 🚫 Raises TypeError: 'bool' object shouldn't be callable
if e book.revealed():
    print('The e book is revealed.')
Enter fullscreen mode

Exit fullscreen mode

Within the above code, class E-book comprises a property named revealed that defines whether or not the books is revealed or not. Additional down, we outlined a way, additionally named revealed.

Consequently, any reference to revealed returns the property not the tactic. And should you attempt to name this property, it’s best to count on the “TypeError: ‘bool’ object shouldn’t be callable” error.

The tactic identify is_published feels like a safer and extra readable various:

class E-book:
    def __init__(self, title, revealed):
        self.title = title
        self.revealed = revealed

    def is_published(self):
        return self.revealed


e book = E-book('Studying Python', True)

if e book.is_published():
    print('The e book is revealed.')
# Output: The e book is revealed.
Enter fullscreen mode

Exit fullscreen mode

Calling a way embellished with @property decorator: The @property decorator turns a way right into a “getter” for a read-only attribute of the identical identify.

class Person:
    def __init__(self, user_id, energetic):
        self._user_id = user_id
        self._active = energetic

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


person = Person(1, True)

# 🚫 Raises TypeError: 'bool' object shouldn't be callable
if person.energetic():
    print('Person is energetic!')
Enter fullscreen mode

Exit fullscreen mode

You might want to entry the getter technique with out the parentheses:

class Person:
    def __init__(self, user_id, energetic):
        self._user_id = user_id
        self._active = energetic

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


person = Person(1, True)

if person.energetic:
    print('Person is energetic!')

# Output: Person is energetic!
Enter fullscreen mode

Exit fullscreen mode

Downside solved!

Alright, I believe it does it! I hope this fast information helped you repair your drawback.

Thanks for studying.

❤️ You may like:

Понравилась статья? Поделить с друзьями:
  • Booking ошибка при бронировании
  • Bonfiglioli vectron active ошибки
  • Bonecraft ошибка при запуске 0xc0000142
  • Boneco h680 ошибка е3
  • Bomann посудомойка ошибка