[Python-ideas] Tweaking closures and lexical scoping to include the function being defined

Ron Adam ron3200 at gmail.com
Sun Oct 2 22:24:01 CEST 2011


On Sun, 2011-10-02 at 17:16 +0900, Stephen J. Turnbull wrote:
> Nick Coghlan writes:
> 
>  > It isn't quite - the name binding doesn't happen until *after* the
>  > decorator chain has been invoked, so the function is anonymous while
>  > the decorators are executing.
> 
> As I understand the issue here, as far as the decorators are
> concerned, the reference passed by the decorator syntax should be
> enough to do any namespace manipulations that are possible in a
> (non-magic) decorator.  Am I missing something?

I've managed to do it with a function, but it isn't pretty and isn't
complete.  It does work for simple cases.


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.

What you get is a function that can replace the old one, but it's a lot
of work.

A compile time solution would be much better, (and faster), and that is
why it boils down to either special syntax, or a precompile decorator
type solution.

If we could make the co_code object less dependent of the cell reference
objects, then a dynamic run time solution becomes realistic.  But that
would take rethinking the byte code to cell relationships.  I don't
think that is a near term option.

Cheers,
   Ron





More information about the Python-ideas mailing list