[Python-ideas] combining two threads: switch statements and inline functions

Chris Angelico rosuav at gmail.com
Wed Feb 12 00:45:57 CET 2014


On Wed, Feb 12, 2014 at 10:05 AM, Bruce Leban <bruce at leapyear.org> wrote:
> What if we had the ability to write dictionaries with inline functions in
> them.
>
> def sample(i, op, j):
>     switcher = {{
>        '-':: if i > j:
>                  return i - j
>              else:
>                  return j - i;;
>        '+':: return i + j;;
>     }}
>     return switcher[op]()
>
>
> Please don't pay attention to {{ :: ;; }} which would never be the actual
> syntax or what this code is doing (nothing useful) or whether i or j should
> be passed as parameters rather than closure. This is equivalent to:
>
> def sample(i, op, j):
>     def diff():
>         if i > j:
>             return i - j
>         else:
>             return j - i
>     def add():
>         return i + j
>     switcher = {
>        '-': diff,
>        '+': add,
>     }
>     return switcher[op]()
>
>

Hmm. In terms of scoping rules and so on, would it be cleaner to
instead make it more equivalent to a big fat expression? Here's legal,
but somewhat ugly, Python code to do the same thing:

def throw(ex):
    """Raise an exception in an expression context."""
    raise ex

def sample(i, op, j):
    return (
        i + j if op == '+' else
        (i - j if i > j else j - i) if op == '-' else
        throw(ValueError("Unrecognized operator "+op))
    )

If your new syntax translates into this, it'll mandate that the
separate sections all be expressions, but it'll be cleaner in terms of
scoping. Also, the use of 'return' inside the switch costs clarity,
imo; it happens to be valid in your example because the result of
'switch' is being returned, but that's coincidental. Making it
honestly be an expression makes it clearer that it's working with
expressions.

ChrisA


More information about the Python-ideas mailing list