【问题标题】:Python type() function issue, str not callablePython type() 函数问题,str 不可调用
【发布时间】:2013-04-20 00:36:46
【问题描述】:

我正在验证某条数据,在这种情况下,字符串“5”应该无法通过某条验证,因为它需要为 5(一个 int)

print ">>>>", value
bad_type = type(value).__name__
raise TypeError("expected numeric type for {0} but got '{1}'".format(column,bad_type))

打印:

.>>>> five
...
bad_type = type(value).__name__
TypeError: 'str' object is not callable

但是我可以从命令行执行此操作:

python -c "print type('five').__name__"

打印

str

我在这里做错了什么?我想打印已通过但未通过自定义验证的值的类型。

【问题讨论】:

  • 'five' 是一个字符串,'5' 也是。
  • 看起来你在某处定义了一个变量名type
  • 有点跑题了,如果你正在寻找一个python数据验证库,那么你可以看看voluptuous,它很小,界面设计良好,易于扩展。

标签: python string validation typeerror


【解决方案1】:

您确定您没有在某处覆盖type 吗?

另外,这不是 Pythonic 的类型检查方式 - 而是使用:

try:
    my_int = int(value)
except (ValueError, TypeError) as e:
    # raise something

【讨论】:

  • 是的,做到了。感谢您的提醒,我不使用pythonic方式。顺便说一句,我检查 value 是否为 str 的相应方法是什么?
  • @DavidWilliams if isinstance(some_var, str) 在 Py3.x 中,或者通常最好在 Py2.x 中使用 if isinstance(some_var, basestring),所以它涵盖了 unicode 和 str
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-05-05
  • 1970-01-01
  • 2020-09-11
  • 2017-10-01
  • 2012-12-09
  • 1970-01-01
  • 2015-06-07
相关资源
最近更新 更多