views:

94

answers:

1

If I make a class against a local namespace, how exactly does it work? For instance:

>>> def foo():
...     i = 1
...     class bar(object):
...             j = i
...     return bar
... 
>>> dis(foo)
  2           0 LOAD_CONST               1 (1)
              3 STORE_DEREF              0 (i)

  3           6 LOAD_CONST               2 ('bar')
              9 LOAD_GLOBAL              0 (object)
             12 BUILD_TUPLE              1
             15 LOAD_CLOSURE             0 (i)
             18 BUILD_TUPLE              1
             21 LOAD_CONST               3 (<code object bar at 0xb74f8800, file "<stdin>", line 3>)
             24 MAKE_CLOSURE             0
             27 CALL_FUNCTION            0
             30 BUILD_CLASS         
             31 STORE_FAST               0 (bar)

  5          34 LOAD_FAST                0 (bar)
             37 RETURN_VALUE        

The particular lines I'm curious about are these:

             15 LOAD_CLOSURE             0 (i)
             18 BUILD_TUPLE              1
             21 LOAD_CONST               3 (<code object bar at 0xb74f8800, file "<stdin>", line 3>)
             24 MAKE_CLOSURE             0
             27 CALL_FUNCTION            0
             30 BUILD_CLASS

I suppose the biggest thing that I'm wondering is what function is being made and then called? And is this function where the closures are attached to the class, or does that happen elsewhere?

+1  A: 

The whole class body, i.e.

j = i

is a code object, which gets loaded at offset 21 and then invoked at offset 27 via CALL_FUNCTION. The result of the invocation (the local namespace) is then used together with the class name and the bases to create the class. BUILD_CLASS takes three arguments, similar to the type(name, bases, dict) function:

Return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the name attribute; the bases tuple itemizes the base classes and becomes the bases attribute; and the dict dictionary is the namespace containing definitions for class body and becomes the dict attribute.

There's also a very detailed article "Notes on the Python Class Statement" explaining how class creation works.

Torsten Marek