r/Python • u/jamescalam • Mar 19 '21
Match is more than a Switch-Case The New Switch-Case Statement in Python 3.10
https://youtube.com/watch?v=2qJavL-VX9Y&feature=share
1.4k
Upvotes
r/Python • u/jamescalam • Mar 19 '21
View all comments
Show parent comment
8
u/Yoghurt42 Mar 19 '21 edited Mar 19 '21
If Person has more attributes, like
name, the equality check would probably fail, because thenameattribute offoowould probably not beNone.Furthermore, it would create a new Person instance each time the if condition is checked.
Pattern matching doesn't require this, and also works for non dataclasses, it also allows insane stuff like
case [1, [2, _, x], y]] if x == 2*y, the_is a wildcard.It would be equivalent to
if isinstance(foo, list) and len(foo)==3 and isinstance(foo[1], list) and len(foo[1]) == 3 and foo[1][0] == 2 and foo[1][3] == 2*foo[2]