[Python-ideas] switch statement as context manager?
Andrew Barnert
abarnert at yahoo.com
Wed Feb 12 00:42:27 CET 2014
On Feb 11, 2014, at 8:58, "Philipp A." <flying-sheep at web.de> wrote:
> 2014-02-11 17:44 GMT+01:00 Ned Batchelder <ned at nedbatchelder.com>:
>
> If it is one, it’s a good thing to look like one.
>
> well, you also get to remove the repeated variable name.
>
Only by repeating the word "case" instead. Compare your syntax:
switch some_long_expr():
if case(0): pass
if case(1): pass
if case(2): pass
... to what you can already write:
case = some_long_expr()
if case == 0: pass
if case == 1: pass
if case == 2: pass
So you haven't saved anything at all. You've added more syntax, more characters, and an extra level of indentation. (Note that in more realistic uses, with real statements being controlled, your syntax indents them all twice instead of once.)
If you really like using parens instead of equals, you can even do that:
case = some_long_expr().__eq__
if case(0): pass
if case(1): pass
if case(2): pass
Maybe you wanted your switch statement to automatically turn each if case into an elif. If so, then the existing alternative does require an extra "el" at the head of each line... But I think it's a lot clearer that at most one of these things will be executed that way.
Also, of course, the elif chain is more flexible. Consider how hard it would be to write this as a switch:
case = some_long_expr().__lt__
if case(0): pass
elif case(1): pass
elif case(2): pass
Or maybe you wanted it to turn the chain of if case statements into a dict lookup or something. If so, that's even more limited, and a lot more magical, for very little benefit.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140211/d5280b80/attachment.html>
More information about the Python-ideas
mailing list