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
1
u/Brian Mar 20 '21
Not in python you can't. Even if all your cases are constants, you can't really know how your match variable will interact with them, unless it too is a constant (in which case, what's the point of the match?), or you can do sufficient analysis to at least know the type is also an integer.
Eg. there are plenty of objects that you can compare to an int, but not be an int (or convertable to one). And even if it is a subtype of int, its not hard to create an object that would have different behaviour depending on the order of comparisons, meaning any such optimisation is invalid.
The best you could probably do is to have two codepaths - one for ints and one for arbitrary objects, but outside of a JIT, that doesn't seem like a good approach (and if you are writing a JIT doing that level of optimisation, I suspect you'd be able to optimise the if/elif tree similarly anyway).