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

Ryan Gonzalez rymg19 at gmail.com
Wed Feb 12 00:51:36 CET 2014


Uhhh...isn't that the same as a lambda? i.e.:

def sample(i, op, j):
    return {'+': lambda: i+j,
              '-': lambda: i-j if i>j else j-i
}[op]



On Tue, Feb 11, 2014 at 5:45 PM, Chris Angelico <rosuav at gmail.com> wrote:

> 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
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>



-- 
Ryan
If anybody ever asks me why I prefer C++ to C, my answer will be simple:
"It's becauseslejfp23(@#Q*(E*EIdc-SEGFAULT. Wait, I don't think that was
nul-terminated."
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140211/40c9042c/attachment.html>


More information about the Python-ideas mailing list