Lazy evaluation: overloading the assignment operator?

Antoon Pardon apardon at forel.vub.ac.be
Thu May 3 04:42:35 EDT 2007


On 2007-05-03, Terry Reedy <tjreedy at udel.edu> wrote:
>
> "sturlamolden" <sturlamolden at yahoo.no> wrote in message 
> news:1178133344.415521.118710 at n76g2000hsh.googlegroups.com...
>|
>| Python allows the binding behaviour to be defined for descriptors,
>| using the __set__ and __get__ methods. I think it would be a major
>| advantage if this could be generalized to any object, by allowing the
>| assignment operator (=) to be overloaded.
>
> Conceptually, assignment is *not* an operator.  Binary operators take two 
> values (of the same type) and produce a third (usually of either the input 
> type or a boolean) that usually depends on both inputs.  Assignment does 
> nothing of the sort.
>
> In Python, the equal sign is *not* an operator: it is a grammatical symbol. 
> One use of the operator fiction in C is to enable simple chained 
> assignment: a=b=2.  Python does this directly without the fiction.  C's 
> store-and-test usage can be implemented in Python with a 'purse' class.
>
>| One particular use for this would be to implement "lazy evaluation".
>
> Since (in Python, at least) operands are evaluated *before* the 
> operator/function is called, I do not see how.

But they could evaluate to an expression tree instead of the actual
result. This tree could then be evaluate at the moment of assignment.

This is an idea I have been playing with myself in an other context.
You have a class of symbolic names. e.g. First, Last ... You can use
the normal operators to these names, the result will be an expression
tree. So Last - 2 will evaluate to something like

                sub
               /   \
	    Last    2

I want to use this in the context of a table (a list like structure
but with arbitrary start index, which can be negative, so tab[-1]
can't refer to the last element).

So I can use this as follows:

       el = tab[Last - 2]

to access the element two places before the last, because the evaluation
of the tree happens in the __getitem__ method.

I could even write something like:

       el = tab[(First + Last) / 2]

To get at the midle element.

-- 
Antoon Pardon



More information about the Python-list mailing list