In python how to check whether a variable is integer or not..
Found a related question here on SO itself.
Python developers prefer to not check types but do a type specific operation and catch a TypeError
exception. But if you don't know the type then you have the following.
>>> i = 12345
>>> type(i)
<type 'int'>
>>> type(i) is int
True
If you need to do this, do
isinstance( <var>, int )
unless you are in Python 2.x in which case you want
isinstance( <var>, ( int, long ) )
Do not use type
. It is almost never the right answer in Python, since it blocks all the flexibility of polymorphism. For instance, if you subclass int
, your new class should register as an int
, which type
will not do:
class Spam( int ): pass
x = Spam( 0 )
type( x ) == int # False
isinstance( x, int ) # True
This adheres to Python's strong polymorphism: you should allow any object that behaves like an int
, instead of mandating that it be one.
BUT
The classical Python mentality, though, is that it's easier to ask forgiveness than permission. In other words, don't check whether x
is an integer; assume that it is ans catch the exception results if it isn't:
try:
x += 1
except TypeError:
...
This mentality is slowly being overtaken by the use of abstract base classes, which let you register exactly what properties your object should have (adding? multiplying? doubling?) by making it inherit from a specially-constructed class. That would be the best solution, since it will permit exactly those objects with the necessary and sufficient attributes, but you will have to read the docs on how to use it.
>>> isinstance(3, int)
True
See here for more.
Note that this does not help if you're looking for int
-like attributes. In this case you may also want to check for long
:
>>> isinstance(3L, (long, int))
True
I've seen checks of this kind against an array/index type in the Python source, but I don't think that's visible outside of C.
Token SO reply: Are you sure you should be checking its type? Either don't pass a type you can't handle, or don't try to outsmart your potential code reusers, they may have a good reason not to pass an int to your function.
Never. Check. Types.
Do this. Always.
try:
some operation that "requires" an integer
except TypeError, e:
it wasn't an integer, fail.
If you really need to check then it's better to use abstract base classes rather than concrete classes. For an integer that would mean:
>>> import numbers
>>> isinstance(3, numbers.Integral)
True
This doesn't restrict the check to just int
, or just int
and long
, but also allows other user-defined types that behave as integers to work.