Pattern evaluation of match statements in run time

Hello everyone,

I have a question about Match statements evaluation in Python. Currently, I’m reading Python Language Reference. In the section dedicated to Match statement, there is a remark that I cannot understand:

Note: Users should generally never rely on a pattern being evaluated. Depending on implementation, the interpreter may cache values or use other optimizations which skip repeated evaluations.

I don’t get it, if an expression is passed through a match statement, it is supposed to be evaluated. Could you kindly clarify this (possibly with a simple example)?

Thanks in advance

This isn’t talking about evaluating the expression you’re matching, but about the patterns that are being matched against. So for example in thise code:

class Things(Enum):
    First = "first"
    Second = "second"

value = Things.Second

match value:
    case Things.First:
        print("first")
    case Things.First:
        print("redundant first")
    case Things.Second:
        print("second")

The interpreter will always evaluate what value is. But what it is allowed to do is cache that ‘Things.First’ was evaluated to a particular object that doesn’t match against the object in value in the first case and then use that fact to skip the name lookup in the second case.

Of course, in an example like this that doesn’t really do much, but if you had e.g. a match statement with a lot of complicated patterns that are only differentiated by their guards, then it can give you an actual performance improvement. Also, the only pattern evaluations that are allowed to be skipped are ones that are known to be redundant. So this can only ever give you a performance improvement, it won’t change the semantics of which pattern is matched (unless you’re doing weird things with overriding dunders).

2 Likes

I think the main intention is that if you have something like

class MySequence:
    def __getitem__(self, index):
        print("Side effect")
        ...

match MySequence():
    ...

then you can’t make any assumptions about how often the side-effect will happen.

As Imogen says, the aim is to allow optimisations by avoiding duplicate work.

2 Likes