我正在编写一个python(2.7.6)脚本,它从Web服务器中提取JSON数据并将其发布到其他地方。我只想发布那些数字的JSON值,例如没有子对象或字符串。数值很可能会超过int
的大小(在C意义上)。我目前的代码如下:
for metric, currentValue in json.items()
if type(currentValue) is int:
oldValue = previous.get(metric)
if oldValue is None:
oldValue = 0
delta = currentValue - oldValue
publish(metric, delta)
previous[metric] = currentValue
我担心的是型式检查。如果Python决定int
不再合适并使用long
,则意味着某些指标不会发布。如果超过long
该怎么办?
我真正想要的是检查currentValue
是否为数字的方法。
有isdigit
,但不适用于底片或浮点数。
答案 0 :(得分:3)
您应该使用isinstance
代替type
示例 -
isinstance(currentValue, (int, long))
如果你想考虑浮动,那么 -
isinstance(currentValue, (int, long, float))