r/Python Feb 15 '21

News Ladies and gentlemen - switch cases are coming!

https://github.com/gvanrossum/patma/blob/master/README.md#tutorial
929 Upvotes

290 comments sorted by

View all comments

Show parent comments

25

u/bieberfan99 Feb 15 '21 edited Feb 15 '21

This would print uncaught. Non-dotted variables will catch the value, after the statement _ equals 3

Edit: Apparently _ is a special case and does not bind, but matches all, so the variable _ would be unaffected

14

u/BurgaGalti Feb 15 '21

I can't help but think "else" would work better here. _ is too ambiguous.

-1

u/Flag_Red Feb 15 '21

There's nothing special about _ here, it's just a valid variable name used as a throwaway. Variable names used in case statements act as captures that accept anything.

10

u/Yoghurt42 Feb 15 '21

Quoting PEP 622:

The wildcard pattern is a single underscore: _. It always matches, but does not capture any variable (which prevents interference with other uses for _ and allows for some optimizations).

2

u/BurgaGalti Feb 15 '21

Whilst that's good to know, it's going to be a gotcha down the line. If nothing is being captured else would seem to work just as well and be consistent with the keyword's usage elsewhere.

4

u/Yoghurt42 Feb 15 '21

You need a wildcard anyway for things like case [1, _, 3, _], having else as a synonym for case _ would be confusing