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

Bruce Leban bruce at leapyear.org
Wed Feb 12 00:05:53 CET 2014


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]()


I don't know if there's a good idea here, but I do know that this pattern
of writing dispatchable functions like this is fairly common, just as the
switch pattern is. There are some obvious problems, most notably that in
the switch statement, the scope of the statements is the same as the
enclosing scope while in this code, each function has it's own scope.
Notwithstanding that, I thought it was an interesting enough idea to share.

--- Bruce
Learn how hackers think: http://j.mp/gruyere-security
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140211/ad4c51ac/attachment.html>


More information about the Python-ideas mailing list