Python:整数精度和类型检查

时间:2015-07-02 12:14:04

标签: python

我正在编写一个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,但不适用于底片或浮点数。

1 个答案:

答案 0 :(得分:3)

您应该使用isinstance代替type

示例 -

isinstance(currentValue, (int, long))

如果你想考虑浮动,那么 -

isinstance(currentValue, (int, long, float))