[Python-Dev] Re: Nested functions and class scope

John Max Skaller skaller@ozemail.com.au
Wed, 15 Nov 2000 00:25:27 +1100

Guido van Rossum wrote:

> Looks like you are missing the point.  Of course I want to keep the
> class as a local scope *inside the class def*.  

	Ah, ok: seem's I was missing your intent.

> But I need it out of the way when executing methods.  

	I don't think this is the right idea. Consider:

	class X:
		x = 'x'
		def f(self): print x
	a = X()
	a.f() # should print 'x'

and then

	def g(self): print x
	class X:
		f = g
	a = X()
	a.f() # should fail

and then:

	def maker():
		x = 'x'
		def f(self): print x
		return f
	class X:
		f = maker()
	a = X()
	a.f() # should work

The point is that I think there is not really much choice
in the matter: when you lookup an unqualified name in a function,
you must look in the function locals, then in the scope of the
object in which the function is defined, and then in the scope
in which that is defined .. and so ontil you reach the bottom
of the stack (which presumably is 'builtins').

	There's no real issue of keeping the class of the object
of a bound method 'out of the way' when executing the function
of the bound method. The scope of that class should be searched
if, and only if, the function happens to have been defined
inside that class. Note there is no such thing as a method
in python: executing a bound (or unbound) method results
in executing a plain old function.

	You _could_ exclude class scopes from the search stack
associated with a function, and just search locals, then
enclosing functions, then the enclosing module and finally
builtins. But it would be highly inconsistent, and not what
people used to lexical scoping would expect. It will be hard
enough to explain the _consistent_ rule that only local
bindings can be changed by assignments -- unless a global
directive changes that. But that rule IS consistent (and the
global directive much less so!)

	I think there is general agreement that lexically
scoping functions inside functions will not break much code.
Do you have an example of real application code where searching a class
which a function is defined will break code?

John (Max) Skaller, mailto:skaller@maxtal.com.au
10/1 Toxteth Rd Glebe NSW 2037 Australia voice: 61-2-9660-0850
checkout Vyper http://Vyper.sourceforge.net
download Interscript http://Interscript.sourceforge.net