[Python-ideas] Yet Another Switch-Case Syntax Proposal
MRAB
python at mrabarnett.plus.com
Tue Apr 22 21:44:34 CEST 2014
On 2014-04-22 18:39, Andrew Barnert wrote:
> On Apr 22, 2014, at 8:01, "Lucas Malor" <7vsfeu4pxg at snkmail.com
> <mailto:7vsfeu4pxg at snkmail.com>> wrote:
>
>> On 20 April 2014 04:17, Bruce Leban bruce-at-leapyear.org
>> <http://bruce-at-leapyear.org> |python-ideas-at-python.org
>> <http://python-ideas-at-python.org>| <vajg1g2cqt at sneakemail.com
>> <mailto:vajg1g2cqt at sneakemail.com>> wrote:
>>
>>
>> I found that the ugliest part of your proposal since it hides the
>> first case and at the same time makes it appear special when it isn't.
>>
>>
>> Myabe yes, but if you "translate" it in an if-elif, also the if seems
>> to be "special".
>
> Yes, there is a difference, but it's not nearly as dramatic as with your
> version. The conditions still look roughly parallel, only one short word
> away from the indent point, instead of the first one being way off to
> the right.
>
> On Apr 22, 2014, at 8:27, "Lucas Malor" <7vsfeu4pxg at snkmail.com
> <mailto:7vsfeu4pxg at snkmail.com>> wrote:
>
>> Sorry, I didn't read it carefully. Anyway, youe example can be written as:
>>
>> for i in range(5):
>> print(i, end=' => ')
>> if i == 1:
>> print('one')
>> elif i == (2,3):
>>
>> print('tuple(two, three)')
>>
>> elif i in (2, 3):
>> print('two or three')
>> elif i > 3:
>> print('more than three')
>>
>> else:
>>
>> print('unmatched')
>>
>>
>> and it's much simpler to read.
>
> That's pretty much his point. The same can be said for all of your examples.
>
> Your version is only "simpler" in that your "case" and "elcase" are
> spelled "if case" and "elif case" in his. Meanwhile, your version is
> more complex in that the first case is crammed on the same line with the
> "switch". Also, instead of automatically handling tuples in a natural
> and obvious way, you're forced to invent a new builtin class and a new
> display form just to distinguish tuples inline in a case label, and
> still can't easily handle the distinction in a natural and readable way.
> And, while his can be trivially extended to handle other types of
> comparison besides == and in, yours can't. So, you've come up with
> something that's more complex, less natural, and less powerful than what
> we can already do, and the only benefit is a little bit of brevity.
>
[snip]
How about a slightly modified 'if' statement:
for i in range(5):
print(i, end=' => ')
case if i == 1:
print('one')
elif (2, 3): # Same as elif == (2, 3)
print('tuple(two, three)')
elif in (2, 3):
print('two or three')
elif > 3:
print('more than three')
elif is None:
print('None')
elif == 0: # Or just elif 0
print('zero')
else:
print('unmatched')
The 'case' says that you want to test the value of part preceding the
comparator, in this case 'i'.
In the 'elif' conditions, '==' is assumed unless you say otherwise.
More information about the Python-ideas
mailing list