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

Nick Coghlan ncoghlan at gmail.com
Tue Sep 27 19:03:02 CEST 2011


On Tue, Sep 27, 2011 at 12:03 PM, Paul Moore <p.f.moore at gmail.com> wrote:
> 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.

It's actually (kind of) the same in C. Names come from the current or
surrounding scope, or are retrieved from another module by the linker,
with static used as a modifier to alter lifetime or visibility.

At the module level in C, "static VAR = EXPR;" doesn't change the
lifecycle of VAR, but it does change the visibility by hiding it from
the linker.

Inside a function, it doesn't really change the visibility (you can
still only access it from code inside the function), but it does alter
the lifecycle by sharing the attribute across all invocations of the
function. (Since C doesn't have nested functions, such variables
effectively become process global).

That's why I really don't like 'static' as the keyword - it has two
different meanings in C, and C++ added a third by using it to denote
class attributes. Python already adopted that third meaning when Guido
created 'staticmethod', so I'm not a fan of also using it for 'static'
in the "function state shared across invocations" sense. (Although, if
we *did* go that way, I'd probably describe it as "a static method
remains the same regardless of which instance you retrieve it from and
a static reference remains the same across all invocations of the
function")

If we're going to settle for a term with multiple meanings, then I
still think 'nonlocal' is the one that makes the most sense:
- it's already a keyword
- the scope to be described lies between 'local' and the existing
meaning of 'nonlocal' on the visibility scale
- it is suggestive of the fact that the initialisation expression is
not evaluated in the local scope
- the two usages would relate to different aspects of function
closures and use the same underlying implementation at call time

All that 'nonlocal' really says is 'not a local'. Since a function
scoped variable *isn't* a local variable, I don't understand the
preference for the even more vague 'static'. I know which one I'd
prefer to try to explain to someone learning Python that didn't
already know C :)

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia



More information about the Python-ideas mailing list