cascading python executions only if return code is 0

Chris Angelico rosuav at gmail.com
Mon Dec 23 02:35:38 CET 2013


On Mon, Dec 23, 2013 at 12:24 PM, Roy Smith <roy at panix.com> wrote:
> Each SongPicker subclass encapsulates some logic for how to pick the
> next song.  It can also decide if the strategy it implements is
> appropriate for the particular request; create() either returns an
> instance of the class, or None.  Returning None means, "I'm not the
> right picker for this request; try the next one and see what he says".

But in that instance, the picker has done nothing. The main effect is
to return a value, and since it returned None, you go on to do
something else.

This looks fine:

foo = a() or b() or c()

And it also looks like it would be safe to drop one of the calls if
you know it won't succeed:

if no_way_that_b_will_work:
    foo = a() or c()

The point about side effects is that b() still has to be called, here,
and the original statement doesn't make that clear. When you call a
function and ignore its return value, you're clearly doing it for its
side effects. Imagine this:

width_required = max(len(foo),len(bar),len(quux))

Any sane reader is going to assume that the length checks aren't going
to have side effects... but they could! Imagine if testing the length
of something forced it to be loaded into memory, thus triggering any
exception that would otherwise not be triggered until the thing got
loaded much later. Vaguely plausible, but bad design because it's
extremely unclear.

ChrisA



More information about the Python-list mailing list