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

Eric Snow ericsnowcurrently at gmail.com
Tue Sep 27 00:23:16 CEST 2011


On Mon, Sep 26, 2011 at 2:17 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> Indeed, it could be said that the defining feature of a nonlocal
> reference is that it is accessible via the function object, whether
> that's through __defaults__, __kwdefaults__ or __closure__.

First of all, I like the idea.  I do agree that nonlocal is not the
optimal name (neither is static).  However, the concept matches well
enough and it's not like nonlocal is used so much that everyone would
have to rewire their brains.

I do have some questions.  Would the value from the nonlocal-from be
stored in a cell in __closure__ or in a new special attribute?  Would
the name be stored in co_freevars or somewhere else?  I realize that's
an implementation detail and perhaps it's premature to worry about.
Still, I'm curious about if you'll be able to distinguish this kind of
value from existing ones when inspecting function and code objects.

How does this impact the other Python implementations?  I would think
not much, since it's not that different from how closures are already
handled (if I understood the idea correctly).

As Steven already pointed out, this may allow the actual function
object to be referenced in the function body, but not by default.
Sounds good.  However, this hinges on the point at which the cell is
created relative to different results of the compilation process (like
the decorator calls).  From what I understand, this should not be hard
to take care of.  Would it be a big deal to make sure a function's
self-referencing nonlocal-from would work?

As Terry noted, default argument values are sort of read-only.  A
function's __defaults__ (and __kwdefaults__) is writable and bound to
a tuple.  The local name that maps to each value in __defaults__ is
re-initialized for each call.  The proposed nonlocal-from syntax would
not reflect these characteristics.  Instead it is more of a
persistent/static mechanism, just like closures.  So is the
nonlocal-from an alternate closure syntax inspired by the default
argument hack, or should it actually behave more like default
arguments do?

-eric

>
> Regards,
> Nick.
>
> --
> Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>



More information about the Python-ideas mailing list