[Python-ideas] A partial (wacky?) alternative to assignment expressions

Dan Sommers dan at tombstonezero.net
Mon May 14 23:59:04 EDT 2018

On Tue, 15 May 2018 10:35:58 +1000, Steven D'Aprano wrote:

> We would need to flag which expression can be cached because it is
> PURE, and tag how far the CACHE operates over:
>     <BEGIN CACHE> 
>         <PURE>
>             func(arg)
>         <END PURE> 
>         + func(arg)*2 + func(arg)**2 
>     <END CACHE>
> This would tell the compiler to only evaluate the sub-expression 
> "func(arg)" once, cache the result, and re-use it each other time it 
> sees that same sub-expression within the surrounding expression.

Does anyone else remember an ancient Python recipe that looked something
like what follows?

    SENTINEL = object()
    class Magic:
        def __call__(self, arg=SENTINEL):
            if arg != SENTINEL:
                self.value = arg
            return self.value
     magic = Magic()

And then you'd use it something like this:

    if magic(g(x)) != 4:
        print("probably not 4: ", magic())
        print("should be 4: ", magic())

    magic(f(x)) + magic()*2 + magic()**2

It's not perfect, but it's not too much worse than some of the other
suggestions floating around.  Sort of.


More information about the Python-ideas mailing list