"a better input"
Alex Martelli
aleax at aleax.it
Thu May 9 16:05:27 EDT 2002
More information about the Python-list mailing list
Thu May 9 16:05:27 EDT 2002
- Previous message (by thread): "a better input"
- Next message (by thread): What Exceptions are there? (was: "a better input")
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Andrew Dalke wrote: > Alex: >> def isThisAComplexLiteral(this): >> try: complex(this) >> except: return False >> else: return True > > Minor point. "except ValueError:" instead of "except:" as in >>> class X: pass ... >>> complex(X) Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: complex() arg can't be converted to complex >>> X is not a complex literal, yet it doesn't give a ValueError. >>> class Y: ... def __complex__(self): raise RuntimeError, "sneaky" ... >>> complex(Y()) Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 2, in __complex__ RuntimeError: sneaky Now tell me again how to write a function that takes ANY object and just tell me if it's translatable into complex. Are you SURE "except:" is not the right approach...? >> 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, If astr is a string, no. But if you forget the parentheses on the call to raw_input, as I did (more bugs in my coding...), specific exception checking helps;-). > My worry about "except:" is that it ignores KeyboardInterrupt > (if done at just the right/wrong time) and gives false results Yeah, well, what's the vulnerability window? > 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. Sure. But when you have NO idea about the argument, as in the first function, there's really no alternative. You MIGHT catch KeyboardInterrupt earlier if you're the kind who wear braces, a belt, AND clean new undies at all times just in cases belt and braces both fail, though. > And 'True' and 'False'? Nothing like cutting edge CVS Python :) Trying them out (in Python 2.2.1). Still seem a (small) net loss to me, but -- gotta give them a chance, after all. Fair's fair, & all that. Alex
- Previous message (by thread): "a better input"
- Next message (by thread): What Exceptions are there? (was: "a better input")
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list