尝试返回布尔值时的TypeError(“ bool”对象不可迭代”) [英] TypeError("'bool' object is not iterable",) when trying to return a Boolean

查看:1000
本文介绍了尝试返回布尔值时的TypeError(“ bool”对象不可迭代”)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一个奇怪的问题。我有一个返回布尔值的方法。反过来,我需要再次返回该函数的结果,因为我无法直接从前端调用该方法。这是我的代码:

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

这将引发异常:TypeError('bool'对象不可迭代,)

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 (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


推荐答案

回溯:

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.

解决方案是:返回一个可迭代的。我建议您将布尔值转换为字符串( str(False))或将其包含在元组中((False,))。

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.

这篇关于尝试返回布尔值时的TypeError(“ bool”对象不可迭代”)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆