[Python-Dev] Product iteration
Guido van Rossum
guido@beopen.com
Wed, 26 Jul 2000 09:44:05 -0500
> Today inner functions don't create cycles involving local variables.
> Lexical scoping would change that.
Fair enough. To resolve this, an inner function should only have a
reference to the outer function if it actually references the outer
function's locals -- which can be determined at compile time.
> > If you want to use weak references, please try to specify *in detail*
> > which objects would have weak references to which other objects and
> > how the system would resolve these... I'm never sure that things can
> > be made 100% safe using this technique, so it may help to spell it out
> > for me!
>
> OK, how's that: inner functions have weak reference to variables in the
> same scope
>
> def f():
> x = 1
> def g():
> pass
Insert "print x" in the body of g, and "return g" in the body of f.
>
> g would have only a weak reference to "x".
>
> I'm changing "no reference" to "weak reference", so I'm not incrementing
> effective reference counting.
Ehm, I'm always confused by the semantics of weak references (you
could say that I haven't a clue about them), so you'd have to do
better than this.
In any case, in your proposal the weak reference to x would go away
when f returns, so if g is exported from f, it breaks!
def f():
x = 1
def g(): print x
g()
return g
gee = f()
gee()
This would first print 1 (the call to g() inside f()) and then raise a
NameError (probably a new subclass e.g. UnboundOuterNameError).
This behavior is unacceptable, at least to the people who have been
clamoring most for this feature (the Schemers): it is expected that
x is kept alive as long as g lives.
So, try again!
--Guido van Rossum (home page: http://www.pythonlabs.com/~guido/)