To be more specific, if the last `elif` condition permits all remaining permissible conditions (which I suppose would just be whatever is asserted by the proposed syntax), then the else block can just be the raising of the exception.
On Thu, Jul 2, 2020, 7:52 PM Steele Farnsworth <swfarnswo...@gmail.com> wrote: > Assertions aren't guaranteed to be executed and thus should never be used > where raising an error is required. > > `else: raise SomeError('reason')` already has the desired effect, and it's > plenty readable. > > On Thu, Jul 2, 2020, 7:46 PM Artemis <hollyshor...@gmail.com> 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. My proposal is >> to allow the following syntax: >> ``` >> if foo == 1: >> # do a >> elif foo == 2: >> # do b >> else foo == 3: >> # do c >> ``` >> 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/O44732WE7XIF5YRO2JFWDPXMOSSHII4A/ Code of Conduct: http://python.org/psf/codeofconduct/