Evaluation order

Ned Batchelder ned at nedbatchelder.com
Fri Jul 10 14:19:32 CEST 2015


On Friday, July 10, 2015 at 8:04:36 AM UTC-4, candide wrote:
> Le vendredi 10 juillet 2015 04:02:56 UTC+2, Chris Angelico a écrit :
> 
> 
>  
> > I'm not sure what contradiction you're referring to, here. The
> > evaluation that you're pointing out says, as Terry showed via the
> > disassembly, that Python's first action is to look up the name 't' and
> > grab a reference to whatever object it points to. 
> 
> 
> But in order to perform an operation, the interpreter has to evaluate the operands and "evaluating" is not "grabbing a reference to". 
> 
> > The execution of
> > t.sort() has to happen before the multiplication, because of the
> > parentheses.
> >
> 
> 
> 
> Official docs explains what evaluation is :
> 
> When the name is bound to an object, evaluation of the atom yields that object.
> 
> So, since the Python interpreter is performing evaluation from left to right, the first operand of the expression :
> 
> t*(1+int(bool(t.sort())))
> 
> evaluates to [2020, 42, 2015]. Next, the second operatand evaluates to the integer 1. So I was expecting the result to be a shallow copy of the first list [2020, 42, 2015] (the value of t before side effect produced by the sort method). On the contrary, the final result takes into in account the side effect and it is as if the first operand has been evaluated twice before execution of the multiplication operation.

The first operand is t. Evaluating t does not make a copy of t, it is simply
a reference to t.  If t is later modified (by the sort method), the modified
data will be seen when t is used in the multiplication.

Python never implicitly copies lists (or any other data structure).  This
explains more about the mechanics of names and values: http://bit.ly/pynames1

--Ned.


More information about the Python-list mailing list