[Python-ideas] except expression
Chris Angelico
rosuav at gmail.com
Thu Feb 20 16:58:38 CET 2014
On Fri, Feb 21, 2014 at 2:22 AM, M.-A. Lemburg <mal at egenix.com> wrote:
>>> os.remove('/') except IOError return None # is really bad style
>> Do you mean because it's not very readable (I agree) or because it's necessarily a bad thing to do
>> (I disagree, particularly if we chose a less drastic example)?
>
> The above is the procedure example I was talking about above.
>
> I find this an even worse style than the open() error, since
> there's absolutely no need to use an expression for this - the
> os.remove() will never return a value, so you don't need
> an expression.
And that's why I, too, decry this as a bad use of the feature. It's
like writing:
os.remove(fn) or None
which implies (a) that os.remove() might return something other than
None, and (b) that the value of the expression is important. Both
implications mislead the reader. The insertion of a single line break
will do it. Let it stand that:
try: os.remove(fn)
except OSError: pass
and there you are, out of your difficulty at once!
(Or, as mentioned, contextlib.suppress.)
ChrisA
More information about the Python-ideas
mailing list