Python style questions

Alex Martelli aleaxit at yahoo.com
Fri Mar 16 16:56:30 EST 2001


"François Granger" <francois.granger at free.fr> wrote in message
news:1eqdo5u.1xxmzfi2kjk0qN%francois.granger at free.fr...
> Aahz Maruch <aahz at panix.com> wrote:
>
> > In article <98tb91$9t9$1 at saltmine.radix.net>,
> > Cary O'Brien <cobrien at Radix.Net> wrote:
>
> > >3. I really miss not having a "switch" or "case" statement.  Sniff.
>
> > Use a dictionary.
>
> Some code snippet as exemple ?
> At this point, I can't imagine a good way, and I don't remember seeing
> something on this.

There are several ways you can use a dictionary to dispatch pieces
of code; any callable (function or otherwise) can be the value that
corresponds to a given key.  Somewhat less obvious, and thus less
advisable, is to use compiled fragments (and exec to run them) as
said values.

To give one toy example, suppose there is some current code you
have that is:

def toy1(fileob, operation, *data):
    if operation=='leggi': return fileob.read(*data)
    elif operation=='scrivi': return fileob.write(*data)
    elif operation=='chiudi': return fileob.close(*data)
    else: raise ValueError, operation

and you're pining to be able to code this as a switch on the
operation rather an an if/elif tree.  OK, easy:

def toy2(fileob, operation, *data):
    switch = {'leggi': fileob.read, 'scrivi': fileob.write,
        'chiudi': fileob.close }
    return switch[operation](*data)

(it raises a KeyError rather than ValueError if it fails, but
if that's important you can catch this and raise whatever),
or, a syntax-sugar alternative:

def toy3(fileob, operation, *data):
    return {'leggi': fileob.read,
        'scrivi': fileob.write,
        'chiudi': fileob.close }[operation](*data)

although I far prefer the toy2 version.


If you give us a specific, similarly-small example that
you dream to be able to code with a switch (and are
presumably now coding with if/elif), we can help you
translate this into some form of dispatching...


Alex






More information about the Python-list mailing list