[Python-Dev] classes and cell variables question

Nick Coghlan ncoghlan at gmail.com
Thu Dec 21 10:48:04 CET 2006


tomer filiba wrote:
> to my understanding of the object model, the code of snippet 1
> and snippet 2 should be equivalent. a class is just a "special function"
> that returns its locals automatically and passes them to the metaclass
> constructor:

PEP 227 (Statically Nested Scopes) covers this in detail (and it echoes 
Guido's earlier message - the lexical scoping skips class statements because 
class attributes are intended to be accessed via attribute reference on the 
class or instance, not as a bare name).

You'll probably find the resulting behaviour less surprising if you think of 
class creation in terms of the exec statement rather than as involving any 
kind of function definition:

   d = dict()
   exec <class body> in globals(), d
   mcl = _determine_metaclass(d, <class bases>) # Not magic, but close ;)
   cls = mcl(<class name>, <class bases>, d)

Class bodies actually have more in common with module level code than they do 
with function bodies (e.g. see how far you get trying to pass a function's 
co_code object to the exec statement - it breaks for reasons somewhat related 
to what we're discussing here).

To go back to your original example, the second snippet should actually look 
more like this:

--- snippet 2a ---
body = """
x = 5
def g(self):
     print "g", x
"""

d = dict()
exec body in globals(), d
barcls = type("barcls", (object,), d)
------

.>>> barcls().g()
g
Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   File "<string>", line 4, in g
NameError: global name 'x' is not defined

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://www.boredomandlaziness.org


More information about the Python-Dev mailing list