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

Paul Moore p.f.moore at gmail.com
Tue Sep 27 18:03:54 CEST 2011


On 27 September 2011 10:35, Nick Coghlan <ncoghlan at gmail.com> wrote:
> If someone can understand the concept of function scoped variables at
> all, then they'll be able to understand the difference between
> 'nonlocal VAR' and 'nonlocal VAR from EXPR'. Given past history, I
> seriously doubt our ability to come up with a keyword for function
> scoped variables that is any more intuitive than a variation on
> nonlocal.

I think I'm starting to get o the point where I understand "nonlocal
VAR from EXPR" when I see it. But that doesn't mean it's becoming
clearer, rather it means that I'm learning to mentally translate it to
"static VAR = EXPR" - or own, or whatever - the concept doesn't have a
clear name to me, which is why choosing a keyword isn't easy, but
whatever it is, it's not really internalised as "nonlocal".

On the other hand, I do (sort of) understand "nonlocal VAR" as meaning
"look outside for VAR" directly. Only somewhat, because I don't think
"nonlocal" is a particularly good name even for that concept, but that
ship's sailed.

> We would then have the following hierarchy of visibility:
>
> Local scope (VAR = EXPR): visible from current function invocation
> Function scope (nonlocal VAR from EXPR): visible from all invocations
> of this function
> Lexical scope (nonlocal VAR; VAR = EXPR): visible from outer function
> where VAR is a local and all invocations of this and any peer
> functions
> Module scope (global VAR; VAR = EXPR): visible from all code in the
> current module
> Process scope (import builtins; builtins.VAR = EXPR): visible from all
> code in the current process
>
> For name *lookup*, lexical scoping, module scoping and process scoping
> can all happen implicitly when a name doesn't refer to a local.
> Function scope lookup would only happen with an explicit declaration
> (regardless of how it was spelt).

Nice summary, but it does emphasise that function scope is (still) an
odd one out, as it's not available for lookup without a declaration.
So we're close, but things still aren't completely unified. And yes, I
know that lookup semantics are so baked into the language that they
aren't going to change - that's the point, think of it the other way
round, that declaring variables as function-scope is odd, because it's
the only one that doesn't have an implicit form for lookup semantics
of code later in the function.

Meh. I tried to give an example of what I mean, to make it clearer,
but I can't quite get one to work right now, and I need to go. I'll
let it stew for a while and try to clarify a bit more later.

Paul.

Paul.



More information about the Python-ideas mailing list