在Python中查找类型 - TypeError:'unicode'对象不可调用

8

我正在尝试确保在Python中一个对象是字符串类型(用于Google应用引擎)。我这样做是为了在其超过500字节时将其更改为db.Text类型。然而,我不断收到错误提示:TypeError 'unicode' object is not callable

    if type(value) in types.StringTypes and len(value) > 499:
        value = db.Text(value)
    setattr(entity, key, value)

我应该使用什么来测试对象的类型是否为字符串?


你试图将 value 变量更改为 db.Text 吗? - inspectorG4dget
你为什么要进行这种转换?你的列需要被索引吗?如果需要,为什么超过512个字节的内容不被索引无关紧要? - Nick Johnson
嘿,尼克,我进行这次对话的原因是因为每当字段大于500字节时会抛出异常,显然你必须切换到未索引的“文本”属性超过500字节? - Chris Dutrow
5个回答

6
我认为你只需要从types.StringTypes中删除括号,因为它是一个元组(不可调用,因此会出现错误)。或者你的代码实际上正在使用StringType,这意味着你的代码正在创建一个新的字符串实例而不是返回str类型。无论哪种方式,都似乎是一个笔误。请参阅文档

我尝试了两种方式,但出现错误。不过这个可以解决问题:isinstance(value, types.StringTypes)。 - Chris Dutrow

4

你为什么要调用 types.StringTypes?它是一个元组:

>>> types.StringTypes
(<type 'str'>, <type 'unicode'>)

使用isinstance(value, types.StringTypes) and len(value) > 499来判断value是否为字符串类型且长度大于499。


1

Greg Haskins 是正确的

>>> types.StringTypes()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object is not callable
>>> types.StringTypes
(<type 'str'>, <type 'unicode'>)

你能做吗?

if type(variable_name) == type("")

1

编辑:糟糕!我看错了types.StringType,而不是types.StringTypes,所以测试应该是:

if type(value) in types.StringTypes and len(value) > 499:
    value = db.Text(value)

主要问题在于 OP 代码中 types.StringTypes 后面有括号。

原文: 这里有几个问题:

  • 如果 value 包含 Unicode,使用 type() 进行测试将返回 types.UnicodeType
  • types.StringType 是一个常量,而不是函数,因此去掉括号。
  • 此外,types.StringType 不可迭代,因此使用 == 或 is 进行测试。

因此,您的测试可能如下所示:

if ((type(value) == types.StringType) or (type(value) == types.UnicodeType)) and len(value) > 499:
    value = db.Text(value)

@DutrowLLC:请查看我的更新答案,以便与types.StringTypes一起使用。 - GreenMatt
如果type(value)在types.StringTypes中并且len(value)> 499:仍然会引发相同的错误。也许你对它不可迭代是正确的? - Chris Dutrow
或者使用 isinstance(value, basestring) - Nick Johnson
@DutrowLLC:你确定你使用的是types.StringTypes(以“s”结尾),而不是types.StringType(结尾没有“s”)吗?这就是导致我的第一个答案有点偏离的原因。此外,如果你使用的是旧版本的Python,你可能会遇到那个错误,因为文档表明types.StringTypes是在2.2中引入的。 - GreenMatt
是的,我进行了双重检查,我正在使用types.StringTypes。我正在使用Python 2.7。 - Chris Dutrow

0

我更喜欢使用isinstance(object_to_be_checked, str)


3
小心使用这个。在Python 2.x中,这对于Unicode字符串或其他类似字符串的对象是无效的。更好的方法是使用 isinstance(obj, basestring),这仍然无法处理非内置的类似字符串的对象,但可以处理Unicode字符串和“普通”字符串。 - Joe Kington

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接