Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError("'bool' object is not iterable",) when trying to return a Boolean

I am having a strange problem. I have a method that returns a boolean. In turn I need the result of that function returned again since I cant directly call the method from the front-end. Here's my code:

# this uses bottle py framework and should return a value to the html front-end
@get('/create/additive/<name>')
def createAdditive(name):
    return pump.createAdditive(name)



 def createAdditive(self, name):
        additiveInsertQuery = """ INSERT INTO additives
                                  SET         name = '""" + name + """'"""
        try:
            self.cursor.execute(additiveInsertQuery)
            self.db.commit()
            return True
        except:
            self.db.rollback()
            return False

This throws an exception: TypeError("'bool' object is not iterable",)

I don't get this error at all since I am not attempting to "iterate" the bool value, only to return it.

If I return a string instead of boolean or int it works as expected. What could be an issue here?

Traceback:

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable
like image 947
DominicM Avatar asked Jul 13 '13 12:07

DominicM


People also ask

How do I fix bool is not iterable?

The Python "TypeError: 'bool' object is not iterable" occurs when we try to iterate over a boolean value ( True or False ) instead of an iterable (e.g. a list). To solve the error, track down where the variable got assigned a boolean and correct the assignment.

What is bool object in Python?

The bool() function returns the boolean value of a specified object.

Is bool data type iterable?

The error TypeError: argument of type 'bool' is not iterable is due to checking the value in Boolean variable. If the right iterable object is passed in the membership operator, such as tuple, set, dictionary, list etc., then the error will not occur.

What does type object is not iterable mean?

If you are running your Python code and you see the error “TypeError: 'int' object is not iterable”, it means you are trying to loop through an integer or other data type that loops cannot work on. In Python, iterable data are lists, tuples, sets, dictionaries, and so on.


1 Answers

Look at the traceback:

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable

Your code isn't iterating the value, but the code receiving it is.

The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)) or enclose it in a tuple ((False,)).

Always read the traceback: it's correct, and it's helpful.

like image 91
Marcin Avatar answered Oct 06 '22 01:10

Marcin