cascading python executions only if return code is 0

Roy Smith roy at panix.com
Sun Dec 22 20:24:10 EST 2013


In article <52b782db$0$6599$c3e8da3$5496439d at news.astraweb.com>,
 Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:

> Code that relies on side-effects is usually a sign of poor 
> design.

I don't understand what you're trying to say there.  A bit later in your 
post, you wrote:

try:
    a()
    b()
    c()
except SomeError:
    handle_error()

Clearly, since the return values of a(), b(), and c() aren't saved, the 
only reason they're getting called is for their side effects.  And I 
don't see anything wrong with that.

BTW, there's a pattern we use a bunch in the Songza server code, which 
is sort of this, but in reverse.  We'll have a bunch of possible ways to 
do something (strategies, to use the pattern vernacular), and want to 
try them all in order until we find one which works.  So, for example:

        classes = [ClientDebugPicker,
                   StatefulSongPicker,
                   SWS_SequentialSongPicker,
                   StandardSongPicker]
        for cls in classes:
            picker = cls.create(radio_session, station, artist)
            if picker:
                return picker
        else:
            assert 0, "can't create picker (classes = %s)" % classes

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".



More information about the Python-list mailing list