Closures in python
David Eppstein
eppstein at ics.uci.edu
Sun Sep 21 17:36:09 EDT 2003
In article <HBF.200309217by at bombur.uio.no>,
Hallvard B Furuseth <h.b.furuseth(nospam)@usit.uio(nospam).no> wrote:
> JCM wrote:
> > >>> def foo():
> > ... x = [3]
> > ... def bar():
> > ... x[0] += 1
> > (...)
> >
> > This is actually one of my biggest complaints about Python. I'd like
> > syntactic disambiguation between definition and assignment in order to
> > have control over which scope you're assigning into.
>
> Maybe Python could be changed to let 'foo.x' inside function foo mean
> the x variable in foo?
But the x variable does not live on the foo function object, it lives on
the stack frame created by the current call to foo.
So something more indirect, like scope(foo).x, would make more sense,
where scope() inspects the call stack looking for calls to foo and
returns an object with appropriate __getattr__ and __setattr__ methods.
This may be implementable now, by someone who knows more about python
introspection than I do. I tried doing it with inspect.stack, but it
doesn't work -- I can find the right frame and get it's f_locals
dictionary, but this gives read-only access to the true frame's locals.
--
David Eppstein http://www.ics.uci.edu/~eppstein/
Univ. of California, Irvine, School of Information & Computer Science
More information about the Python-list
mailing list