In which order many functions are executed in a python code

Terry Reedy tjreedy at udel.edu
Fri Jun 9 19:18:52 EDT 2017


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].

> In this case, func2() will be called before func1(). This is because 
> func1() needs three parameters and one of those parameters is the return 
> value of func2().

Given r = f[a](1, g[b](c)), your rule above does not determine whether 
f[a] or g[b] is determined first.  In at least some C implementations, 
g[b] would be.  Since the call g[b](c) could affect the bindings of f, 
a, and the result of f[a], the rule that f[a] is calculated before g, b, 
c, g[b], and g[b](c) may make a real difference.

> Python can not know the return value of func2() without calling it. 
> Therefore, to be able to call func1() and give it its three parameters, 
> it must first call func2() to find out what that third parameter value is.
> 
> It's equivalent to:
> 
> func2result = func2(x, y)
> result = func1(1, 2, func2result)

Since the func2 call could have the side effect of rebinding 'func1', 
this is not exactly equivalent.

> If that is _not_ what you are talking about, then like Thomas says - you 
> need to paste some code and explain what you are confused by.

Indeed.

-- 
Terry Jan Reedy




More information about the Python-list mailing list