check if object is number
Francis Girard
francis.girard at free.fr
Sun Feb 13 12:57:27 EST 2005
Le vendredi 11 Février 2005 20:11, Steven Bethard a écrit :
> Is there a good way to determine if an object is a numeric type?
> Generally, I avoid type-checks in favor of try/except blocks, but I'm
> not sure what to do in this case:
>
> def f(i):
> ...
> if x < i:
> ...
>
> The problem is, no error will be thrown if 'i' is, say, a string:
>
> py> 1 < 'a'
> True
> py> 10000000000 < 'a'
> True
>
> But for my code, passing a string is bad, so I'd like to provide an
> appropriate error.
>
This is a very bad Python feature that might very well be fixed in version 3.0
according to your own reply to a previous thread. This problem clearly shows
that this Python feature does hurt.
Here's a transcript of the answer :
> Yes, that rule being to compare objects of different types by their type
> names (falling back to the address of the type object if the type names
> are the same, I believe). Of course, this is arbitrary, and Python does
> not guarantee you this ordering -- it would not raise backwards
> compatibility concerns to, say, change the ordering in Python 2.5.
>
> > What was the goal behind this rule ?
>
> I believe at the time, people thought that comparison should be defined
> for all Python objects. Guido has since said that he wishes the
> decision hadn't been made this way, and has suggested that in Python
> 3.0, objects of unequal types will not have a default comparison.
>
> Probably this means ripping the end off of default_3way_compare and
> raising an exception. As Fredrik Lundh pointed out, they could, if they
> wanted to, also rip out the code that special-cases None too.
>
> Steve
Regards
Francis Girard
More information about the Python-list
mailing list