Python 2.7和Python 3.3之间的函数类型检查

Rus*_*hal 1 python types function python-2.7 python-3.x

在我的函数中,我检查输入的类型以使其有效(例如 - 对于检查'n'的素数的函数,我不希望'n'作为字符串输入).检查longs和ints 时会出现问题.在Python 3.3中,他们删除了long-type号,因此出现以下问题:

def isPrime(n):
    """Checks if 'n' is prime"""
    if not isinstance(n, int): raise TypeError('n must be int')
    # rest of code
Run Code Online (Sandbox Code Playgroud)

这适用于v2.7和v3.3.但是,如果我在Python 2.7程序中导入这个函数,并long为'n' 输入一个-type号,就像这样:isPrime(123456789000)它显然会引发一个TypeError因为'n'是类型的long,而不是int.

那么,如何检查longs和ints的v2.7和v3.3是否有效?

谢谢!

Jon*_*nts 7

我能想到的一种方式是:

from numbers import Integral

>>> blah = [1, 1.2, 1L]
>>> [i for i in blah if isinstance(i, Integral)]
[1, 1L]
Run Code Online (Sandbox Code Playgroud)

编辑(在@martineau的深刻评论之后)

Python 2.7:

>>> map(type, [1, 1.2, 2**128])
[<type 'int'>, <type 'float'>, <type 'long'>]
Run Code Online (Sandbox Code Playgroud)

Python 3.3:

>>> list(map(type, [1, 1.2, 2**128]))
[<class 'int'>, <class 'float'>, <class 'int'>]
Run Code Online (Sandbox Code Playgroud)

这个例子仍然表明使用isinstance(n, numbers.Integral)但更加连贯.