isFloat: Without Exception-Handling

Mark McEahern marklists at mceahern.com
Fri Sep 20 15:50:15 CEST 2002


[Thomas Guettler]
> Is there a way to write the following method without using exceptions?

Please help me understand your aversion to the original code you posted.
IMHO, it has several salient characteristics:

1.  It works.
2.  It works.
3.  It works.

Did I forget to mention:

It works.

Anyway, I'd modify your original function slightly to use True/False
(builtin as of 2.2.1) and to be explicit about which errors we're ignoring:

def isFloat(s):
    is_float = True
    try:
        float(s)
    except (ValueError, TypeError), e:
        is_float = False
    return is_float

assert isFloat(1.2)
assert isFloat(1)
assert not isFloat(4+0j)
assert not isFloat("banana")
assert not isFloat(isFloat)
assert not isFloat(__import__)
...etc...

<wink>

Cheers,

// m

-





More information about the Python-list mailing list