[Python-Dev] Accessing globals without dict lookup

Tim Peters tim.one@comcast.net
Sun, 10 Feb 2002 20:14:07 -0500


[Aahz]
> Let me play stupid for a sec: how does a compiled code object get
> created?

Explicitly via passing strings to compile/exec/eval or via execfile, or
implicitly due to the normal operation of class, def and lambda statements,
and the interactive prompt.

> Is Tim saying that one can pass foo.bar to exec, where bar() is a function
> in module foo?

No, foo.bar is a function object, meaning basically that it's a code object
bound to a specific name and a specifc bag of globals, and whose default
argument values (if any) have been computed and frozen based on those
globals.  You can pass foo.bar.func_code to exec, though (that's the raw
code object).  Note that marshal can't handle function objects, but can
handle code objects, and some people make extremely heavy use of extracting
code objects for marshaling, then later unmarshaling and exec'ing them.
When I'm tempted to exec, I'm more likely to use compile() in a separate
step (to get better control over errors) and exec the resulting code object.

> ...
> Alternatively, can we change the semantics of exec to require the use
> of compile() to generate code objects?
> (compile() on an existing code object would do an explicit rewrite of
> the bytecode.)

I didn't follow this, but am not sure it would help if I did <wink>.