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?
The whole class body, i.e.
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_CLASStakes three arguments, similar to thetype(name, bases, dict)function:There’s also a very detailed article “Notes on the Python Class Statement” explaining how class creation works.