[Python-ideas] A partial (wacky?) alternative to assignment expressions
Franklin? Lee
leewangzhong+python at gmail.com
Mon May 14 22:07:45 EDT 2018
On Mon, May 14, 2018 at 8:35 PM, Steven D'Aprano <steve at pearwood.info> wrote:
> I'm hoping that the arguments for assignment expressions will be over by
> Christmas *wink* so as a partial (and hopefully less controversial)
> alternative, what do people think of the idea of flagging certain
> expressions as "pure functions" so the compiler can automatically cache
> results from it?
>
> Let me explain: one of the use-cases for assignment expressions is to
> reduce repetition of code which may be expensive. A toy example:
>
> func(arg) + func(arg)*2 + func(arg)**2
>
> If func() is a pure function with no side-effects, that is three times
> as costly as it ought to be:
>
> (f := func(arg)) + f*2 + f**2
>
> Functional languages like Haskell can and do make this optimization all
> the time (or so I am lead to believe), because the compiler knows that
> func must be a pure, side-effect-free function. But the Python
> interpreter cannot do this optimization for us, because it has no way of
> knowing whether func() is a pure function.
While I support the idea of marking pure functions somehow, automating
this optimization is not a simple matter.
Haskell (or at least its standard compiler) usually doesn't do it for you:
"""
GHC doesn't actually perform CSE as often as you might expect. The
trouble is, performing CSE can affect the strictness/laziness of the
program. So GHC does do CSE, but only in specific circumstances ---
see the GHC manual. (Section??)
Long story short: "If you care about CSE, do it by hand."
"""
https://wiki.haskell.org/GHC_optimisations#Common_subexpression_elimination
Pure functions do, however, help with constant propagation during compilation.
A PyPy blog post goes into a bit of detail about how pure functions
can be helpful:
https://morepypy.blogspot.com/2011/03/controlling-tracing-of-interpreter-with_15.html
More information about the Python-ideas
mailing list