Friday, March 27, 2009

About Python Namespaces

Jeff Rush is up front in ballroom E (our plenary room with the dividers installed). We're waiting for the signal from A/V (a Quakerly silience..., keys tapping). Jeff is our Dallas chief.

Namespaces are mappings, the foundation of Python: globals, locals, (builtins). Lexical context, dynamic context (Python uses lexical context for closeures).

Name binding occurs during assignment, defs, imports, arg declaration, for statements, except clauses, as a result of closures. Code objects + namespaces = coll stuff. Steve makes this same distinction ("object spaces").

They're not namespaces, run inside namespaces, are not function obejcts. import, compile() exec, execfile etc., are code object creators (compilers we could say). The "assembly language" of Python. He's showing compiling on his slide. from dis import dis. co = compile(blah blah). ns = {}, exec co in global_ns, local_ns.

He's showing us where the code objects are. Just fragments, not everything defines a code object. You get these trees of code objects, with the module the outer code object. Good use of pointers for assignment.

When you instantiate a module, you get this "knitting" among code objects, assembled into a constellation of objects (not all of which are code objects).

The object tree is what's in the .pyc file. The namespace assembles the code object starting with the root node, throws that away, gives us the new namespace in sys.modules. You don't get your function objects until post-execution. The body of a class is actually a function. The post-execution view is closer to what my level understands, so its good to see pre-execution diagrams.

Generators keep the local namespace around, but functions and methods throw it away. A closure is a nested scope. My way of returning a derivative function (from a function) is a good example of closure.

He's giving some really excellent code examples, going by lickity-split. These slides better be on the web someplace. I need to come back to this stuff, think about it some more. globals() is locals() -- when is this true?