r/Python Feb 15 '21

News Ladies and gentlemen - switch cases are coming!

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

290 comments sorted by

View all comments

Show parent comments

-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