【问题标题】:Why would Python give me a "TypeError: argument of type 'UserAgent' is not iterable" in a non-iteration type of operation?为什么 Python 会在非迭代类型的操作中给我一个“TypeError:'UserAgent' 类型的参数不可迭代”?
【发布时间】:2011-03-13 11:57:45
【问题描述】:

我有一个 BaseHandler 类,它是我的 AppEngine 站点中 Tipfy RequestHandler 的子类。在其中,我为移动设备设置了一个“穷人的”浏览器嗅探器,其类属性(元组)包含设备名称。

在随后的方法中,我循环遍历元组中的设备名称,并根据请求对象中的用户代理字符串检查它们。如果我得到一个匹配项,我将一个名为“is_mobile”的实例属性设置为 True。

然而,在该方法中,Python 给了我一个“TypeError:'UserAgent' 类型的参数不可迭代”错误,我不明白为什么,因为它抱怨的行不是(就我明白)一个循环。

代码如下:

class BaseHandler(RequestHandler, AppEngineAuthMixin, AllSessionMixins):

    mobile_devices = ('Android', 'iPhone', 'iPod', 'Blackberry')

    ....

    def detect_mobile_devices(self):
        found_device = False

        for device in self.__class__.mobile_devices:
            if device in self.request.user_agent:
                found_device = True
                break

        self.is_mobile = found_device

这是 Python 不喜欢的那一行:

File "/path/to/project/app/apps/remember_things/handlers.py", line 56, in detect_mobile_devices
if device in self.request.user_agent:

【问题讨论】:

    标签: python google-app-engine tipfy


    【解决方案1】:

    表达式

    device in self.request.user_agent
    

    将首先尝试调用

    self.request.user_agent.__contains__(device)
    

    如果此方法不存在,Python 会尝试遍历 self.request.user_agent 并将遇到的每个项目与 device 进行比较。显然,self.request.user_agent 的类型既不允许 .__contains__() 也不允许迭代,因此出现错误消息。

    另见the documentation of membership test in Python

    【讨论】:

    • 谢谢!我没有意识到这一点。
    猜你喜欢
    • 2017-05-03
    • 2012-04-26
    • 1970-01-01
    • 2022-11-08
    • 2019-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多