1

I'm writing a python (2.7.6) script that pulls JSON data from a webserver and publishes it elsewhere. I only want to publish those JSON values that are numeric, e.g. no sub-objects or strings. It's very likely that the numeric values will exceed the size of int (in the C sense of size). My current code looks like this:

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

My concern is the type check. If Python decides that int is no longer appropriate and uses long instead it means some metrics will not get published. And what to do if long gets exceeded?

What I really want is a way to check that currentValue is numeric. There is isdigit but that doesn't work for negatives or floats.

James
  • 9,064
  • 3
  • 31
  • 49
  • 2
    [`isinstance(currentValue, (int, long))`](https://docs.python.org/3/library/functions.html#isinstance)? `long` can't get exceeded (unless your RAM does - see e.g. http://stackoverflow.com/q/9860588/3001761), it's arbitrary precision. – jonrsharpe Jul 02 '15 at 12:17
  • 1
    Note that `isdigit` only works for *strings*; if that's what you've got, you will need to convert them to numbers explicitly. – jonrsharpe Jul 02 '15 at 12:20

1 Answers1

3

You should use isinstance instead of type

Example -

isinstance(currentValue, (int, long))

If you want to consider float as well, then -

isinstance(currentValue, (int, long, float))
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
  • 2
    See the [`numbers`](https://docs.python.org/2/library/numbers.html) module for more inclusive types (`numbers.Integral`, for example, includes `int`, `long`, and `bool`). – chepner Jul 02 '15 at 13:08