python isinstance(n, int) and int(n) == n
Question: Two functions:

    
    
    def check(n):
        if int(n) != n:
            print("int(n) != n")
        else:
            print("int(n) == n")
    

and

    
    
    def check2(n):
        if not isinstance(n, int):
            print("n is not an int")
        else:
            print("n is an int")
    

What's the difference? And which one is better?


Answer: The second one actually works (because it doesn't error out on something not
coerceable to int), but it really depends what you want to do. If you're
working in pure Python, the best thing to do is duck type - a function like
this is a slight tweak on check that will check if something is an integral
value (so, for example, it will work with `2.0` and also `2`, but not `'2'`
but not error out:

    
    
    def check3(n):
        "prints 'n is an int' if the value is integral"
        try:
            val = int(n)
            if val == n:
               print("n is an int")
        except ValueError:
            pass # return False would also work
        print("n is not an int")
    

In contrast, if it's important to know the difference between `1.0` and `1`
(e.g., you have an int64 ndarray), then you'd want to use your instance
checking `check2`, because it will let you know that it's _exactly_ an int.

It boils down to this question: must it _be_ an int or just _act_ like an
integral number? If it has to be an int, then use check2, if it has to _act_
like an int, use check (but probably modify it to be within a try/except like
shown above).

The other option is to take advantage of abstract base classes to allow for
int-likes (for example, numpy int dtypes that are integral, but not actually
subclasses of int), using an abstract base class, `numbers.Integral`.

    
    
    def check4(n):
        if isinstance(n, (int, numbers.Integral)):
            print("n is an int")
        else:
            print("n is not an int")
    

As an aside, `check4` is _much_ slower than _check3_ , because the lookup for
instance checking on abstract base classes involves some processing.

