Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Switch statements have fall-through behavior that you need `break` to avoid (in most languages); sometimes this is what you want, but only rarely.

One trick I've seen people do in Python is to use a dict; define lambdas for each case, and then key the dict on your value that you would switch on, and invoke the lambda (or use existing functions).

    def fake_switch(self, thing):
        {
            'foo': self.do_foo,
            'bar': self.do_bar,
            'frog': self.blast_vent_core
        }[ thing ]()
I am doing a poor job of explaining _why_ one might want to do that, but one advantage is that you can verify that the right callbacks were called in tests, and also verify that each callback behaves right when invoked, since they are just references to methods or functions. I'm not sure if doing this would get marks for cleverness and testability, or would get one criticized for excessive cleverness. As the reviewer of the code when a coworker wrote it, I recall liking it, though.


Thanks to both of you for the info. I haven't played with lambdas much yet, perhaps this is the time to start :)


Lambdas in Python are somewhat limited - the syntax allows for only one expression. You can use inner (nested) functions however.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: