static variables?

Alex Martelli aleax at aleax.it
Fri Nov 22 09:08:08 EST 2002


Erik Max Francis wrote:
   ...
> think, where such a system (namely where the objects are stowed in the
> function and then are copied each time they're needed when a default
> argument is needed) would have unexpected or undesired behavior.  For
   ...
>> A better way might be to compile the expression and store off the
>> bytecode, to be executed each function invocation if nothing is bound
>> to the parameter - sort of an extra, optional, first line to the
>> function.
> 
> This would be another example of a reasonably straightforward
> implementation that would get the desired effect as well.


The semantics of the two mechanisms are very different.  Consider e.g.:

aa=bb=23

def f(x=[aa, bb]): print x
f()

aa=44
f()


Under the "evaluate at def time, copy at every call time" mechanism, just 
like with the current semantics, this prints:
[23, 23]
[23, 23]

Under the "delayed evaluation at every call time only" mechanism, though, 
it prints:
[23, 23]
[44, 23]

Now, these effects (plural) can't BOTH be "the desired effect" (singular), 
can they?  They're different... so, if one is desired, then the other is 
not.

Similarly, it's easy to show differences between using copy and using 
deepcopy as variants of the "copy every time" choice.

Another part of the effect that some newbies seem to sometimes desire comes 
with:

def f(x=anobj, y=x.anattribute):

and here I think that only delayed evaluation (with a different scope, 
local to f rather than global) might satisfy that.


I think a case can be made for either of the two extremes as being SIMPLE 
to explain and conceptualize: either the current one (evaluation at def 
time in global scope) or the one that makes:

def f(x=<expression>):

identical to what currently must be expressed somewhat like:

def f(x=<privatesentinel>):
  if x is <privatesentinel>: x=<expression

"Intermediate" solutions, with calls to copy or deepcopy seemingly 
appearing out of nowhere, seem clunky and complicated mechanisms to
me in comparison.


Alex




More information about the Python-list mailing list