Python 3.10 introduced a cool new match operator. You decide to use it in the new board game that you're writing.
https://gist.github.com/545510302d5bbbeae8fd132bdbfe8999
Then you try it out (got to love the REPL):
https://gist.github.com/4940229ade88f2f42cb34829a1c7c38a
Hmm... 5 is way less than 100 (MAX_X
), why then?
Then you remember that match
is structural pattern matching, not a switch
statement, it match by structure, not by value. Which mean the first case will match any 2 item tuple
. In your case, it'll set MAX_X
to 5 and MAX_Y
to 100 and will not advance any point. Lucky for you, inside advance
MAX_X
and MAX_Y
are local variables and won't overwrite the global ones.
There are two ways to fix this issue. The first is to use guards.
https://gist.github.com/7aaefe2b009e046ec0088e77e9290e02
The second option, is to convert MAX_X
and MAX_Y
to enums:
https://gist.github.com/569142edea1fd08bdd9ea944ba7c840e
Structural pattern matching is an exciting new feature, time will tell how it'll be used and what best practices will emerge for using it. In the meanwhile, you can read more about them here.
If you liked this article, take a look at my Python Brain Teasers book which is filled with these kind of puzzles and their answers. It'll make you a better Python programmer, and ... it fun!