python返回布尔值对象,尝试返回布尔值时的TypeError(“ bool”对象不可迭代”)...

开发者在使用BottlePy框架时遇到问题,尝试从后端方法返回布尔值到前端,却触发了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/')

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

解决方案

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.

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值