Python Mystery Theatre -- Episode 2: Así Fue

Duncan Booth duncan at NOSPAMrcp.co.uk
Tue Jul 15 05:37:58 EDT 2003


"Helmut Jarausch" <jarausch at igpm.rwth-aachen.de> wrote in 
news:3F13C137.6090705 at igpm.rwth-aachen.de:

> 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)

There is no 'obviously' about it.

'once' is a name bound to the function.
'f' is another name bound to the same function.
There are no references to references here.

It is true that the function knows that its name is 'once', and indeed the 
code object used by the function also has a name 'once', but:

  def once(x): return x
  f = once

Both 'f' and 'once' are names bound directly to the same function object.

 +------+              +----------------+
 | once |------------->| function object|
 +------+              +----------------+
                         ^
 +------+                |
 |   f  |----------------+
 +------+

Assignment in Python simply makes a new binding to the existing object. It 
doesn't matter what type the existing object was, it never makes a copy of 
the object nor adds an extra level of indirection.

> 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' ?
> 
You did get the current value of 'ref' so that the first time callee was 
bound to the same function that 'once' and 'ref' were bound to, and the 
second time the local variable 'callee' was bound to the same function that 
'twice' and 'ref' were bound to at that time.

Each time you call 'caller' you get a new local variable, none of the 
values are preserved from the previous call. If you want to preserve state, 
save an attribute in a global, or better a class instance.


-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list