[Python-ideas] why not try without except?
denis.spir at free.fr
Sun Apr 26 10:51:08 CEST 2009
Le Sun, 26 Apr 2009 11:05:56 +1000,
Steven D'Aprano <steve at pearwood.info> s'exprima ainsi:
> On Sat, 25 Apr 2009 11:32:39 pm Georg Brandl wrote:
> > And while we're at it, let's introduce
> > on error resume next:
> > foo()
> > bar()
> > baz()
> Is that meant to be a serious suggestion or a sarcastic rejoinder?
It is certainly sarcastic -- never mind -;) Georg could have saved some typing by reading comments and examples...
What I had in mind (and commented), is precisely not a syntactic construct able to catch any exception for a whole block of statements. E.g. an example like
can only catch AttributeError for 'fillColor' or for 'fill'.
Now I realise that what I miss is a kind of handy, clear, and not misuseable idiom for coping with undefined variables/attributes/parameters.
Otherwise one needs to fall back to the reflexive-check-instead-of-try idiom:
or use try... except ... pass.
'None' is also often (mis)used for this. People aware of the issues with None will rather have a custom undef-meaning object instead. Right?
UNDEF = object()
But this also requires checking instead of trying, doesn't it? It also requires binding a default UNDEF value to names that, conceptually speaking, can well remain undefined (UNDEF is still a value, as well as None).
This is rather close to the use of Haskell's optional type (I guess it's called 'Maybe' -- checked, see e.g. http://en.wikibooks.org/wiki/Haskell/Hierarchical_libraries/Maybe). And I think Scala has something similar, too. But these special types fit well the semantics of statically-typed and compile-time-checked languages.
One issue with None is that it can be used as a valid value. A workaround may be a user-unsettable undef-meaning builtin value. Or a builtin isDef() function. Still, both of these methods require checking. While the 'option' (or '?') proposal allows trying-instead-of-checking.
Why not restrict it to a set of sensible exception types? for instance (this is what I would like):
except (NameError, AttributeError):
Moreover: Haskell's Maybe type can be used for return values. I really wonder about python action-functions (that do not produce a result) returning None instead of nothing at all. This is another story, indeed, but I see it closely related at the meaning level.
searched = seq.find(....) # may not return anything, not even None
option print searched
la vita e estrany
More information about the Python-ideas