patma icon indicating copy to clipboard operation
patma copied to clipboard

Allow the implementation some flexibility when compiling patterns.

Open brandtbucher opened this issue 4 years ago • 2 comments

We may be able to make more powerful optimizations possible in the future if we clearly and explicitly state that there are no guarantees as to the order (or number of times) that different parts of the matching machinery are invoked on patterns, as long as the order and semantics of name bindings, guards, and bodies remain unchanged.

For example, here is a case where we could one day get away with:

  • Only checking if stuff is a length-one sequence and extracting the contained value once.
  • Only using Bar.__match__ and friends once.
  • Only using Foo.__match__ and friends once.
match stuff:
    case [Bar(100) | Foo(100)] | [Foo(42)]:
       ...
    case [Bar(42)]:
        ...

A somewhat weaker variant of this would be to allow individual patterns to be rewritten, but for no data to be shared or reordered between distinct cases. The first case in the example above would still benefit from this, but not the second.

brandtbucher avatar Jun 01 '20 19:06 brandtbucher

Allowing the number of calls to Foo.__match__ 8(with the same arg) etc. to vary seems fine to me. It should be a "pure function" of the target object anyway.

I think it's fine to do this even across multiple cases.

gvanrossum avatar Jun 01 '20 20:06 gvanrossum

It might not necessarily be so much a question about the future of the CPython implementation as such. Rather, there are various Python implementation that work hard to optimise code, e.g. PyPy or Numba. By explicitly allowing for such optimisations, we are probably paving the way for some exciting work from these projects.

Tobias-Kohn avatar Jun 01 '20 20:06 Tobias-Kohn