"a better input"

Andrew Dalke dalke at dalkescientific.com
Thu May 9 12:59:01 EDT 2002


Alex:
> def isThisAComplexLiteral(this):
>     try: complex(this)
>     except: return False
>     else: return True

Minor point.  "except ValueError:" instead of "except:" as in

try:
  complex(this)
except ValueError:
  return False
else:
  return True

> Of course, the real approach is less silly:
>
> def cooked_input(astr=None):
>     if astr=None: astr=raw_input
>     for atype in int, long, float, complex:
>         try: return atype(astr)
          except ValueError: pass   # I changed this line
>     else:
>         return astr

There may be some exceptions those throw besides ValueError,
but I don't know of any, and I just scanned floatobject.c and
intobject.c to veriy those cases.

My worry about "except:" is that it ignores KeyboardInterrupt
(if done at just the right/wrong time) and gives false results
for typos, like

  complx(s)

(raises a NameError, which is caught by the exception and turned
into a False.  It's catchable in testing, but not as easy to
identify as a traceback which points out the error location.

                    Andrew
                    dalke at dalkescientific.com
P.S.
  And 'True' and 'False'?  Nothing like cutting edge CVS Python :)






More information about the Python-list mailing list