4 ms·
I've done this before, I think of it as a more powerful form of a switch statement. I'd love to hear why you think it's not ideal.
by davidrusu 12y ago
I've done this before, I think of it as a more powerful form of a switch statement.
I'd love to hear why you think it's not ideal.
- SiVal 12y agoI don't think it's more powerful in any way than an if-elif-elif-else which, for what it's worth, I consider the Pythonic way. Having said that, just because I consider something more Pythonic doesn't mean I prefer it. I've worked in a lot of languages over the years and still work in several in addition to Python. I really enjoy Python, but I prefer techniques that are more universal in many cases. For example, I prefer the idiom of looping over a list index to using Python's "enumerate" in most cases, because index looping is a common cross-language idiom and enumerate usually doesn't offer any benefit I value more than universal obviousness. Other things such as Python's `for item in items` looping style are both VERY Pythonic and much nicer than, say, index looping, so I would almost always prefer such idioms. The above switch -> function pointerish thing is clear to me from years of C/C++, but it is both less generally applicable across languages than if-elif... and less Pythonic, so I would prefer the if-elif... approach. Obviously a matter of preferences, but since you asked....
- aidos 12y agoIt's strange that you would prefer `for item in items` but not `for i, item in enumerate(items)`. So in that case you'd manually do the `for i in range(len(items))...`? I sometimes see this in code and think to myself, whoever wrote this needs to learn themselves some idiomatic python :) I don't think there's much point trying to force stuff that makes sense in one language into another language. Play to a languages strengths and all that. I think you're right about if-elif generally being more powerful than the jump table. Though the jump table is useful in that you can define it in one place and use it in another.
- zo1 12y ago"I'd love to hear why you think it's not ideal." I'm not the poster you posed that question to. But for me, the one big drawback of using that idiom is that the function signatures have to be identical. So you either have to resort to args/kwargs, or you have an additional intermediary method between the actual "guts" of what you're calling, and the "switch" statement. Or you live with the fact that you're passing unused/unnecessary parameters to your functions.
- myg204 12y agoGood point, and in that case, I would say this idiom is not so great really. For functions with the same signature, it's a fine solution I think.