Re: Python Mystery Theatre -- Episode 2: Así Fue

Helmut Jarausch jarausch at igpm.rwth-aachen.de
Tue Jul 15 04:54:15 EDT 2003


Fredrik Lundh wrote:
> Helmut Jarausch wrote:
> 
> 
>>OK, I believe to know why the last line
>>print '3' three times, since only a reference
>>to 'f' is stored within the lambda expression
>>and this has the value 'thrice' when 'print'
>>is executed.
>>
>>But how can I achieve something like an
>>evaluation of one indirection so that
>>a reference to the function referenced by 'f'
>>is stored instead.
> 
> 
> assuming you meant "the function reference by 'f' when the lambda
> is created", the easiest solution is to use default argument binding:
> 
>     flam = [lambda x,f=f: f(x) for f in funcs]
> 
> the "f=f" construct will bind the inner name "f" to the current value of
> the outer "f" for each lambda.
> 
> the nested scopes mechanism is often introduced as the "right way" to
> do what was done with argument binding in earlier versions of Python.
> however, nested scopes bind *names*, while argument binding binds
> *values*.

Many thanks for that hint,
still a part of the question remains (unclear to me)

Obviously Python allows references to references, since
e.g. 'once' (the 'name' of a function) is a reference to
the code and 'f' is a reference to that reference. (you call it
name binding)
A similar situation arises in Maple and there one has the choice
to either derefence all references down to the real object
or to just derefence a single time.

Example

def once(x): return x
def twice(x): return 2*x
ref= once
def caller():
     callee=ref   # (*)
     print callee(1)

caller()  # prints 1
ref= twice
caller()  # prints 2  so that demonstrates name binding

how can I get the current value (like 'xdef' in TeX)
of 'ref' in the assignment (*) above, so that
'callee' becomes an (immutable) reference to 'once' ?

Thanks for your patience,

Helmut.

-- 
Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany





More information about the Python-list mailing list