[Dev] Python dynamic vs lexical scoping

David McCusker david at osafoundation.org
Sun Nov 17 21:57:32 PST 2002


Jeremy Hylton wrote:
> The question is not whether Python uses dynamic or static scoping, but
> whether a nested function has access to variables defined in the
> containing function.  Python has always been statically scoped, but
> before Python 2.1 free variables were always resolved in the global
> and builtin namespaces.

Aha, that's very interesting, since it means the explanation found in
http://www.hetland.org/python/instant-python.php is completely wrong
when it says the problem is dynamic instead of lexical scoping.

You're saying the old Python didn't have closures, and that PEP 227
(which I see you wrote yourself) suggested adding them.  The examples
on http://www.hetland.org/python/instant-python.php are now explained
because the lexical bindings in effect when the inner function was
defined are no longer in existence at call time, so the global defs
are the only ones visible at that time.

Basically, the variables were not free a definition time, but they
became free later because no closure was created to preserve the
bindings from the time a nested function was created.  I'm not sure
it's valid to say a language has lexical scoping when it does this
with nested functions, but I suppose it doesn't really matter.

It's interesting that giving default values to method parameters in
the old Python seemed to create a closure to keep original bindings,
and that this could be used as a workaround.

Thanks, I don't think I would have figured out the material I found
was giving the wrong interpretation for quite a while.

--David McCusker







More information about the Dev mailing list