Q: Python 2.0 preliminary features?

Eric Jacobs x at x.x
Sat Oct 9 02:02:28 EDT 1999


Preston Landers wrote:
> 
> And just because I like to start flame wars, I'll go ahead and add my
> own feature to the wishlist:  nested scopes / namespaces.  Is this a
> pipe dream, or just too hard to implement given the internal structure
> of Python (which I'm not really familiar with.)  Maybe I'm just going
> about it all wrong, but it seems like much of my code would be cleaner
> given arbitrarily nested scopes.  I've discussed this with people
> before on c.l.python but never really got an explanation that made
> sense (to me) for the way it is now.

I too am for rethinking of the way that scopes are handled in Python.
But I'm not too sure what you mean by "arbitrarily nested" scopes.
Python is a bit different from other languages with scope rules
for at least two reasons: that there is no need to predeclare any
variables, and that functions are fully first-class.

Consider this function:

	def f(y):
		f1 = lambda y=y: y.foo
		f2 = lambda foo=y.foo: foo
		return (f1, f2)

Here the two functions that are returned do completely different
things. The first retrieves the current value of foo for the
object that was originally passed. The second always returns 
a constant, whatever value that foo had when the function was
called. If we could simply write:

		f3 = lambda : y.foo

the automatic scope nester would have to decide what you meant.
Kind of a stupid example, because usually you would want the
function that looked up the current value, although I actually
have had occasions where I needed the constant bird, and I was
kind of glad that Python made you spell it out.

Traditionally, scope would be resolved by chaining the local
scope (inside the lambda) to the next outer scope (f()'s 
locals). Python already does something similar to this, in the
way that an object chains from its own dir() to its class.
But that would be very tricky to do for functions, because
sub-functions are first class and can exist even when their
containing function has exited. If the sub-function chained
to the containing function's namespace, that would mean that
the whole stack frame would essentially have to be moved
to a "heap frame" and ref-counted and handled like an
independent object!

That seems a bit extreme. But anything short of that, and you
still have that barrier to cross (going from the containing
function's namespace to where the subfunction can pick it
up.) Being able to specify how that translation takes place
is very important for defining functions that can be used
somewhere other than where they were created (a very useful,
very cool feature of Python IMO.)




More information about the Python-list mailing list