[Python-Dev] Nested scopes.

Thomas Wouters thomas@xs4all.net
Sun, 4 Feb 2001 03:01:13 +0100


So I've been reading python-list and pondering the nested scope issue. I
even read the PEP (traded Sleep(tm) for it :). And I'm thinking we can fix
the entire nested-scopes-in-combination-with-local-namespace-modifying-stmts
issue by doing a last-ditch effort when the codeblock creates a nested scope
_and_ uses 'from-import *' or 'exec'. Looking at the noise on python-list I
think we should really try to do that. Making 'from foo import *' and 'exec'
work in the absense of nested scopes might not be enough, given that a
simple 'lambda: 0' statement would suffice to break code again.

Here's what I think could work: In absense of 'exec' or 'import*' in a local
namespace, compile it as currently. In absense of a nested scope, compile it
as 2.0 did, allowing exec and import*. In case both exist, resolve all names
local to the nested function as local names, but generate LOAD_PLEASE (or
whatever) opcodes that do a top-down search of all parent scopes at runtime.
I'm sure it would mean a lot of confusion if people mix 'from foo import *'
and a nested scope that intends to use a global, but ends up using a name
imported from foo, but I'm also sure it will create a lot less confusion
than just breaking a lot of code, for no apparent reason (because that is
and will be how people see it.)

I also realize implementing the LOAD_PLEASE opcode isn't that
straightforward. It requires a pointer from each nested scope to its parent
scope (I'm not sure if those exist yet) and it also requires a way to search
a function-local namespace (but that should be possible, since that is what
LOAD_NAME does.) It would be terribly inefficient (relatively speaking), but
so is the use of from-import* in 2.0, so I don't really consider that an
issue. The only thing I'm really not sure of is why this hasn't already been
done; is there a strong fundamental argument against this aproach other than
the (very valid) issue of 'too many features, too little time' ? I still
have to grok the nested-scope changes to the compiler and interpreter, so I
might have overlooked something.

And finally, if this change is going to happen it has to happen before
Python 2.1, preferably before 2.1b1. If we ship 2.1-final with the current
restrictions, or even the toned-down restrictions of "no import*/exec near
nested scopes", it will probably not matter for 2.2, one way or another.

Willing-to-write-it-if-given-an-extra-alpha-to-do-it-ly y'rs,
-- 
Thomas Wouters <thomas@xs4all.net>

Hi! I'm a .signature virus! copy me into your .signature file to help me spread!