check if object is number

George Sakkis gsakkis at rutgers.edu
Fri Feb 11 18:08:54 EST 2005


> > So what you're saying is that 3 <= "3.0" should not be allowed, but
> > 3 <= SomeUserDefinedNumericClass(3) is ok, although your program knows
> > nothing a priori about SomeUserDefinedNumericClass. The idea suggested
> > before, try if "x+1" fails or not does not get you far; any class that
> > overrides __add__ may fool this test:
> >
> > class Dummy:
> >     def __add__(self,other):
> >         return 0
>
> Right but by the same logic, we can fool protocols that are builtin to
> Python:
>
> py> class C(object):
> ...     def __iter__(self):
> ...         return 0
> ...
> py> for x in C():
> ...     print x
> ...
> Traceback (most recent call last):
>    File "<interactive input>", line 1, in ?
> TypeError: iter() returned non-iterator of type 'int'
>
> I'm not trying to catch the case where someone is deliberately violating
> the protocol.  Only the case where they've provided an object that
> doesn't conform to the protcol.

Note however that in my example there's no TypeError; 0 (or any value for that matter) is perfectly
valid for __add__, while __iter__ must return an iterator.

> Clearly, complex objects don't conform to the protocol I want -- they
> don't support comparisons to ints.  This is easy to check:
>
> try:
>      x <= 1
> except TypeError:
>      raise TypeError('%s does not support comparisons to ints' %
>                      type(x).__name__)
>
> Now str objects also don't conform my protocol -- they aren't comparable
> to integers in any meaningful sense.  Ideally, I should be able to use
> the same code as above for str objects (and get a TypeError like "str
> objects cannot be compared with int objects"), but unfortunately, the
> Python wart of cross-type default comparisons gets in the way.  I look
> forward to the day when Python 3.0 removes such comparisons.  =)

Me too... the way comparison works as of now is error-prone, to say the least. Comparing ints with
strings is no more valid than adding them, and python (correctly) raises TypeError for the latter,
but not for the former. For the record, here's the arbitrary and undocumented (?) order among some
main builtin types:

>>> None < 0 == 0.0 < {} < [] < ""  < ()
True

George





More information about the Python-list mailing list