-1. Assertions are ignored when Python is run with -O, so we definitely don't want to encourage relying on asserts to ensure users pass the correct value. But even if that wasn't an issue, I consider the `else: ValueError()` to be significantly more readable.
Otherwise, the alternative offered by Steve Barnes of using a dict for the input options works well when you have a large number of possible inputs with entirely different behaviors. Although I'd say for anything with around 5 or less options, the `else: ValueError()` makes more sense for its simplicity. On Thu, Jul 2, 2020 at 7:43 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/3DFZ24QV36BG644KGTQZWPFNYDK7CJRO/ Code of Conduct: http://python.org/psf/codeofconduct/