简体   繁体   中英

Check whether variable is int or long in Python 2.7 and 3.x

I want to have a input type check for an API function that works in Python 2.7 and up. The API takes a timestamp in milliseconds since epoch as its parameter. I need to ensure that the input is a positive number.

Depending on the value, Python 2.7 will represent a timestamp as an integer or a long . So the type check would look like this:

isinstance(timestamp, (int, long)) 

However, the long type was merged with int for Python 3. In fact, the long type no longer exists. So the above line would cause an exception. Instead, the check would look like this:

isinstance(timestamp, int) 

For compatibility with Python 2.7, I tried casting the timestamp to an int. However, the cast operation still returns a long if the value is outside of the integer range. This means the check will fail for any timestamp after Sun Jan 25 1970 20:31:23 . See also the answer to this question .

What would be the best way to make this a generic check that works in both versions of Python?

检查任何整数,使用numbers.Integral

isinstance(timestamp, numbers.Integral)

Or follow this cheat sheet for python 2-3 compatiable code

Just install future package: pip install future

# Python2
>>> x = 9999999999999999999999L
>>> isinstance(x, int)
False
>>> from builtins import int
>>> isinstance(x, int)
True

If you want to check that the type of variable is exactly equals to intgiven then just do it using type() function:

import sys
if sys.version_info >= (3,0):
    long = int

type(v) in (int, long)

Borrowing from the six package:

import sys

PY3 = sys.version_info[0] == 3

if PY3:
    integer_types = (int,)
else:
    integer_types = (long, int)

long_type = integer_types[0]

Then you can check with

if isinstance(value, integer_types):

and cast with

value = long_type(value)
# This will works in both Python2, Python3
# Just check type of the variable and compare
import time
timestamp = time.time()

type(timestamp) == int
type(timestamp) == float

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM