types
Python 2 では、次のモジュールを使用できます。
>>> import types
>>> var = 1
>>> NumberTypes = (types.IntType, types.LongType, types.FloatType, types.ComplexType)
>>> isinstance(var, NumberTypes)
True
複数の型に対してテストするためのタプルの使用に注意してください。
内部では、 などIntType
の単なるエイリアスです。int
>>> isinstance(var, (int, long, float, complex))
True
このcomplex
型では、Python が複素数をサポートするようにコンパイルされている必要があります。これを防ぎたい場合は、try/except ブロックを使用します。
>>> try:
... NumberTypes = (types.IntType, types.LongType, types.FloatType, types.ComplexType)
... except AttributeError:
... # No support for complex numbers compiled
... NumberTypes = (types.IntType, types.LongType, types.FloatType)
...
または、型を直接使用するだけの場合:
>>> try:
... NumberTypes = (int, long, float, complex)
... except NameError:
... # No support for complex numbers compiled
... NumberTypes = (int, long, float)
...
Python 3types
では、標準の型エイリアスがなくなり、常に有効になり、 vsの違いcomplex
がなくなったため、Python 3 では常に次を使用します。long
int
NumberTypes = (int, float, complex)
最後になりましたが、numbers.Numbers
抽象基本型(Python 2.6 の新機能) を使用して、上記の型から直接派生しないカスタム数値型もサポートできます。
>>> import numbers
>>> isinstance(var, numbers.Number)
True
このチェックでは、オブジェクトも返さTrue
れます。decimal.Decimal()
fractions.Fraction()
complex
このモジュールは、型が有効になっていることを前提としています。そうでない場合は、インポート エラーが発生します。