In which order many functions are executed in a python code

Terry Reedy tjreedy at udel.edu
Fri Jun 9 23:57:45 EDT 2017


On 6/9/2017 8:14 PM, Erik wrote:
> On 10/06/17 00:18, Terry Reedy wrote:
>> On 6/9/2017 6:00 PM, Erik wrote:
>>> On 09/06/17 19:39, sondes kalboussi wrote:
>>>> Am a bit confused I was thinking that the order of execution of
>>>> functions in a code is from the first to the last function but
>>>> sometimes it is the opposite, for instance, some parameters or
>>>> outputs from the second function are called in the first one even
>>>> thou they are not global, any hints ?
>>>
>>> As a complete and utter guess, I assume you are talking about 
>>> something like:
>>>
>>> result = func1(1, 2, func2(x, y))

>> On the right side of '=', Python evaluates expressions, to the extent 
>> possible, left to right.  The result of each evaluation is an object. 
>> In the above, the order is func1, 1, 2, func2, x, y, _tem = func2(x, 
>> y), func1(1, 2, _tem).  Note that function expressions can be more 
>> complicated than just a name, as in func_array[selector].
> 
> Terry, how does this help the OP who is obviously a learner, understand 
> their problem?

Which is unclear in the absence of any example.

Erik, calm down.  I did not jump on what you said, I added detail. 
python-list is a public forum and answers are for any one who reads the 
thread, either now or in the future.  That is why answers are posted 
publicly, not privately.  (I happen to more often answer questions on 
StackOverflow, where questions and answers are more explicitly intended 
to constitute a growing database of programming knowledge, and where 
they are much more easily searched.)

That said, Python's uniform left-to-right rule is a simplifying rule 
which I found very helpful when *I* was a beginner.  It was a relief 
after my previous experience with a language (C) where so many behaviors 
are 'implementation defined' or worse, 'undefined'.  So I thought it 
might be helpful to this beginner and I expect it will be to someone. 
Knowing order of evaluation is crucial to understanding code where most 
anything might have a side-effect.

For example, what should be the order of output of this code?

def echo(x):
     print(x)
     return x

d = {echo(1): echo(2), echo(3): echo(4)}

In 3.5+, it is 1,2,3,4, as the rule says.  In early 3.x, 2.7, and some 
undetermined earlier versions, it was 2,1,4,3*.  When the bug was 
discovered, there was a thought that we should just document the 
exception, because fixing the bug could break code.  The decision was to 
leave maintenance versions, including 2.x, alone and fix the bug in the 
next py 3 version.

* If one views dict displays as abbreviating a series of assignments, 
such as d[echo(1)] = echo(2); d[echo(3)] = echo(4), the reversal makes 
some sense.

-- 
Terry Jan Reedy




More information about the Python-list mailing list