On 03/07/2020 00:39, Artemis wrote:
Often, I know that a variable should have one of a set of values, and I want to 
determine which one, with an if/elif/else clause. This looks something like 
this:
```
if foo == 1:
     # do a
elif foo == 2:
     # do b
elif foo == 3:
     # do c
else:
     raise ValueError('foo must be 1, 2 or 3')
```
Sometimes, I just do
```
if foo == 1:
     # do a
elif foo == 2:
     # do b
else:
     # do c
```
But this is less readable and allows errors to slip past.
Quite right. :-)
  My proposal is to allow the following syntax:
```
if foo == 1:
     # do a
elif foo == 2:
     # do b
else foo == 3:
     # do c
```
Objection 1:  "else foo==3:" is too similar to "else: foo==3" and "else: foo=3"
which are already legal syntax.
Objection 2: Code maintenance.  Suppose you wanted to add an extra case where foo was 4. You would either have to put the "foo==4" case before the "foo==3" case, which might be undesirable for stylistic reasons, or you would have to *change* "else foo==3:" to "elif foo==3:", and then add "else foo==4:" Summary: You'd be better off writing it in the first place as per your code snippet, which is
nice, simple, straightforward and easy for someone reading it to understand.
then if you want to add an extra case, you can just insert the code for it in the obvious way.
Admittedly in this example you'd also want to change the error message to

        'foo must be 1, 2, 3 or 4'
but if you look at the code, this is kinda obvious (and if you forget to do it, 
it's also
obvious to someone reading the code).

Objection 3:  Not worth forcing Python users to learn a new construct for not 
much benefit.

Or perhaps the more readable version:
```
if foo == 1:
     # do a
elif foo == 2:
     # do b
else assert foo == 3:
     # do c
```
Both of these options are backward compatible, since currently nothing is 
allowed between the `else` and the `:`.
This would be roughly equivalent to
```
if foo == 1:
     # do a
elif foo == 2:
     # do b
else:
     assert foo == 3
     # do c
```
But shorter and more readable, since it puts the assertion at the same levels 
as the others. Thoughts?
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/ZKAQK7YTOR2GVVFZFVO3U22WYJHVC3KE/
Code of Conduct: http://python.org/psf/codeofconduct/
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/OY2II2KFFCUQT3YXHE4TVXQS7LXZBJCQ/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to