tags:

views:

59

answers:

3

i will be comparing two values like this:\

value1>value2

i know that value2 is always an integer, but sometimes value1 is None or a string, how do force the comparison ONLY if value1 is numerical?

value1 is a decimal

+2  A: 

Python 3

try:
    value1 > value2
except TypeError:
    pass

Python <3

if isinstance( value2, int ):
    value1 > value2

This latter is unpythonic, because this type of comparison is unpythonic. You should filter your data first.

katrielalex
can you use this on a decimal also?
I__
Yes. The former because Py3k won't let you compare distinct types, and the latter because we *only* allow `int`s. You should try and think a bit about what the code is doing before asking such simple questions.
katrielalex
http://stackoverflow.com/questions/3375913/python-is-there-an-iserror-function
I__
That's completely unrelated.
katrielalex
+2  A: 
try:
    int(value1) > value2
except (TypeError, ValueError):
    pass
brianz
can you use this on a decimal also?
I__
Yes, you can. Those two exceptions are raise when trying convert None or another object which can't be coerced to an int. A float (1.23) can be coerced, so not exception will be raised.
brianz
+2  A: 
if value1:
    Decimal(value1) > value2
WoLpH
can you use this on a decimal also?
I__
The `int` cast won't work pleasantly on a decimal. And the `isdigit()` only works on strings. You can check for the existance of `isdigit` with `hasattr` and change the `int` to `Decimal` to make sure you can compare both ints and Decimals.
WoLpH
will isdigit return true on 1.123?
I__
As I said, that only works for strings. However, if your input is sanitized (all the strings can be casted to `Decimal`) than you can do with a simple `if value1` and a `Decimal(value1) > value2`
WoLpH