Created
January 29, 2015 13:09
-
-
Save dmiro/fa05d8337b93532dff36 to your computer and use it in GitHub Desktop.
How to properly use python's isinstance() to check if a variable is a number?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
You can use the types module: | |
>>> import types | |
>>> var = 1 | |
>>> NumberTypes = (types.IntType, types.LongType, types.FloatType, types.ComplexType) | |
>>> isinstance(var, NumberTypes) | |
True | |
Note the use of a tuple to test against multiple types. | |
Under the hood, IntType is just an alias for int, etc.: | |
>>> isinstance(var, (int, long, float, complex)) | |
True | |
The complex type requires that your python was compiled with support for complex numbers; if you want to guard for this use a try/except block: | |
>>> 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) | |
... | |
or if you just use the types directly: | |
>>> try: | |
... NumberTypes = (int, long, float, complex) | |
... except NameError: | |
... # No support for complex numbers compiled | |
... NumberTypes = (int, long, float) | |
... | |
Last but not least, you can use the numbers.Numbers abstract base type (new in Python 2.6) to also support custom numeric types that don't derive directly from the above types: | |
>>> import numbers | |
>>> isinstance(var, numbers.Number) | |
True | |
This module does make the assumption that the complex type is enabled; you'll get an import error if it is not. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment