Python TypeError("'bool' object is not iterable",) 尝试返回布尔值时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17630323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError("'bool' object is not iterable",) when trying to return a Boolean
提问by DominicM
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",)
这会引发异常: 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.
我根本没有收到这个错误,因为我没有试图“迭代” bool 值,只是为了返回它。
If I return a string instead of boolean or int it works as expected. What could be an issue here?
如果我返回一个字符串而不是 boolean 或 int 它会按预期工作。这里可能有什么问题?
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
采纳答案by Marcin
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,)
).
解决方案是:返回一个可迭代对象。我建议您将 bool 转换为字符串 ( str(False)
) 或将其包含在元组 ( (False,)
) 中。
Always read the traceback: it's correct, and it's helpful.
始终阅读回溯:它是正确的,而且很有帮助。