Inada Naoki wrote:
> Since this is very new system, can we have some restriction to allow
> aggressive optimization than regular Python code?
The authors were just discussing a related question yesterday (more
specifically, can the compiler fold `C(<p0>) | C(<p1>)` -> `C(<p0> | <p1>)`).
The answer we arrived at is "yes"; in general patterns may take reasonable
shortcuts, and should not be expected to follow all the same rules as
expressions. This means that users should never count on
`__contains__`/`__getitem__`/`__instancecheck__`/`__len__`/`__match_args__` or
other attributes being looked up or called more than once with the same
arguments, and that name lookups *may* be "frozen", in a sense. We don't feel a
need to cater to code that relies on these side-effecty behaviors (or doing
even nastier things like changing local/global name bindings); in the eyes of
the authors, code like that is buggy.
However, these rules only apply as long as we are still in "pattern-land",
meaning all of our knowledge about the world is invalidated as soon as we hit a
guard or stop matching.
In practice, I am currently experimenting with building decision-trees at
compile-time. Given a match block of the following form:
```
match <s>:
case <p0> | <p1>: ...
case <p2> | <p3> if <g0>: ...
case <p4> | <p5>: ...
```
It's safe to use the same decision tree for <p0> through <p3>, but it must be
rebuilt for <p4> and <p5>, since <g0> could have done literally *anything*.
_______________________________________________
Python-Dev mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-dev.python.org/
Message archived at
https://mail.python.org/archives/list/[email protected]/message/XY3FXVB7HDYJIVKSOOBHW5BV2UB522FL/
Code of Conduct: http://python.org/psf/codeofconduct/