[Python-ideas] For-loop variable scope: simultaneous possession and ingestion of cake

Terry Reedy tjreedy at udel.edu
Mon Oct 6 17:59:34 CEST 2008


Carl Johnson wrote:
> Why does the evil default args hack work? Because it immediately 
> evaluates the argument and stores the result into the lambda object's 
> default values list. So, what we need is a keyword that means 
> "immediately evaluate the argument and store the result, instead of 
> looking up the name again later." Since I can't think of a good name for 
> this, I will use a terrible name for it, "immanentize."

'@' would mostly work, '$' is available, and is used for string 
substitution in other languages.

...

> One interesting side effect of having an immanentize keyword is that in 
> Python 4000, we could (if we wanted to) get rid of the supposed "wart" 
> of having x=[] as a default arg leading to unexpected results for Python 
> newbies. Just make it so that to get the current behavior you type
> 
>  >>> def f(x=immanentize []):
> ...     x.append(1)
> ...     return x
> ...
>  >>> f()
> [1]
>  >>> f()
> [1, 1]

As you said above, immanetize mean evaluate immediate, just as with 
default arg expressions, so immanetize can hardly mean anything extra 
when applied to default arg expressions.  So you really need a new 
'calltime' keyword for not immediate execution.  Unless, of course, you 
are proposing that *all* default arg expressions be, by default, 
repeatedly evaluated at each call (thereby breaking all code depending 
on define-time evaluation).

> Whereas, without immanentize we can do what newbies expect and evaluate 
> the defaults afresh each time.
> 
>  >>> def f(x=[]):
> ...     x.append(1)
> ...     return x
> ...
>  >>> f()
> [1]
>  >>> f()
> [1]

Only some newbies expect this.  The ones like me who get that default 
args are evaluated just *once* never post complaints to c.l.p.  It gives 
a completely biased sample.

In any case, I don't see how you expect this to actually work. What 
object would you have put into the default arg tuple?  What about

a=[]
def f(x=a):
   x.append(1)
   return x

Would you have this magically modified also?  Suppose instead of 'a=[]' 
we have 'from mod import a'.  What about other mutable objects?

Terry Jan Reedy




More information about the Python-ideas mailing list