[Python-ideas] Tweaking closures and lexical scoping to include the function being defined
Ron Adam
ron3200 at gmail.com
Mon Oct 3 08:11:06 CEST 2011
On Sun, 2011-10-02 at 22:32 +0100, Arnaud Delobelle wrote:
> On 2 October 2011 21:24, Ron Adam <ron3200 at gmail.com> wrote:
> > But it isn't easy to do...
> >
> >
> > 1. Creating a dummy function with a __closure__, and taking the parts of
> > interst from it. (Requires exec to do it.)
> >
> > 2. Creating a new byte code object with the needed changes. (Hard to get
> > right)
> >
> > 3. Create a new code object with the altered pieces.
> >
> > 4. Make a new function with the new code object and __closure__
> > attribute. Use the original function to supply all the other parts.
>
> And you've got to take care of nested functions. That is, look for
> code objects in the co_consts attribute of the function's code objects
> and apply the same transformation (recursively). Moreover, you have
> to modify (recursively) all the code objects so that any MAKE_FUNCTION
> is changed to MAKE_CLOSURE, which involves inserting into the bytecode
> a code sequence to build the tuple of free variables of the closure on
> the stack. At this point it may be almost easier to write a general
> purpose code object to source code translator, stick a nonlocal
> declaration at the start of the source of the function, wrap it in an
> outer def and recompile the whole thing!
>
> A simple example to illustrate:
...
> Now imagine we have the non-magic "nonlocal" decorator:
>
> @nonlocal(x=27, y=15)
> def foo():
> def bar():
> return x + y
> return bar
...
I got this much to work..
def foo()
@nonlocal(x=27, y=15)
def bar():
return x + y
return bar
But nothing with nested functions.
It sort of makes me want pure functions with no scope or closures by
default.
Cheers,
Ron
More information about the Python-ideas
mailing list