views:

322

answers:

5

In python how to check whether a variable is integer or not..

A: 

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
Ashish
-1 You should at the very least explain why not to do this. Just posting this code promotes bad Python. (I hate to downvote this, because it's technically correct, but it shouldn't be upvoted.)
katrielalex
There you go. You would be glad to notice it is not up-voted now either.
Ashish
Thanks. Downvote removed. (Though you could be a bit more emphatic about not using `type` =p.)
katrielalex
+5  A: 

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.

katrielalex
Erm, why the downvote?
katrielalex
For Python 2.x to check for an integer you really need to use `isinstance(x, (int, long))`. After all a `long` is an integer too!
Scott Griffiths
Thanks, will mention it. I haven't used Python 2.x for a while =p
katrielalex
Nice one.........
Hulk
+3  A: 
>>> 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.

Matt Joiner
+1: After all, `decimal.Decimal` and `fractions.Rational` often works where you've so carefully checked for `int`. Type checking in advance prevents **legal, appropriate** use. It doesn't prevent any problems.
S.Lott
I had a variable in a dictionary so have to do a type check in this case
Hulk
@Hulk: Why is that case special?
katrielalex
The requirement was such that if value of the variable is not a integer then not to process further..
Hulk
Are you sure that's the requirement? What if somebody makes a `loggedInt` that logs every time it's accessed (!)... shouldn't you accept that as well?
katrielalex
@Hulk: "if value of the variable is not a integer then not to process further" Best handled by exception surrounding the loop. This does not need any type checking.
S.Lott
A: 

Never. Check. Types.

Do this. Always.

try:
    some operation that "requires" an integer
except TypeError, e:
    it wasn't an integer, fail.
S.Lott
It is sometimes necessary to check the type of the object (as you admit in your comment above). Although it's usually misguided there are real use-cases and the language provides the facilities to do it. I don't think that saying never ever do something is helpful or correct.
Scott Griffiths
Can you think of a single instance where you *must* check the type of an object? With the advent of ABCs I think they are probably now gone.
katrielalex
Certainly in terms of efficiency and readable code, yes type checking has proved invaluable to me. For example in an initialiser that takes different types not doing an explicit check can lead to some convoluted and computationally expensive code. I can't really provide a good example in a comment though!
Scott Griffiths
@Scott Griffiths. That's the only counter example. That's why I said "never". It's always important to use universals to force people to think. It's never appropriate to waffle around about special cases.
S.Lott
@Scott Giffiths: Also, "in terms of efficiency" is likely false. Please measure carefully. Except clauses are remarkably efficient.
S.Lott
The efficiency argument isn't just in terms of single statements. I agree that try/except is very efficient and isinstance() is remarkably slow (I have profiled quite a lot). Sometimes to distinguish between, for example, a string and another type of iterable you might have go some way before an exception gets raised (if an exception gets raised at all!) So the time lost is in going half-way through the try clause before being able to bail out. This can also be quite a fragile arrangement and you run the risk that a later change might make the exception not be raised.
Scott Griffiths
@Scott Griffiths: Limiting things to a narrow range of types "can also be quite a fragile arrangement". Someone creates a new type that's perfectly legal, yet prohibited by needless up-front type checking. "you might have go some way before an exception gets raised" is hard to envision without a specific example.
S.Lott
As Scott Griffiths made the statement "a string and another type of iterable you might have go some way before an exception gets raised (if an exception gets raised at all!) So the time lost is in going half-way through the try clause before being able to bail out"There was a scenario as exactly described to be handled if a variable is not integer why process further....
Hulk
@S.Lott :i agree your except clause statement
Hulk
@Hulk: "So the time lost is in going half-way through the try clause before being able to bail out" There is still no actual example of this. I expect that this is trivially preventable without resorting to needless type checking. But without an actual example, I can't correct the error that leads to "going half-way through the try clause before being able to bail out".
S.Lott
@S.Lott:The example i cangive of u is this.I am constructing a dictionary from reading a file row..After reading this and processing it i create another dictionary of the desired values.So for example for reading every line in a file i construct two dictionaries. so if one of the field is not integer i return an exception in which case i dont have to construct the second dictionary dictionary..I hope u understand now..
Hulk
@Hulk: First, an `if` statement doesn't help you check the type. An exception works **faster** than an `if` statement. Second, you can build two dictionaries together, not build one dictionary and then build a second dictionary. The example is not good.
S.Lott
@S.Lott:Point taken..
Hulk
A: 

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.

Scott Griffiths