Observations on the three pillars of Python execution

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sat Aug 6 04:05:01 CEST 2011

Eric Snow wrote:

> On Fri, Aug 5, 2011 at 11:29 AM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>> Do you believe that this process of generating a code object and throwing
>> it away is a part of the Python language specification, which any
>> compiler must do in order to call itself "Python", or a mere
>> implementation detail?
> That's a great point which I hadn't considered.  Honestly, I only used
> my experience with CPython in making these observations.  After
> reviewing the language reference I see that I missed out on a bunch of
> nomenclature that would have made things more clear, and I got a few
> points wrong, which you pointed out.  :)
> Regarding code objects and classes, your are right.  The language
> reference indicates the following:
>     "The class’s suite is then executed in a new execution frame...When
>     the class’s suite finishes execution, its execution frame is discarded
>     but its local namespace is saved." [1]

It turns out that in CPython 2.5 at least, I'm strictly wrong and you got it
right, at least for classes:

>>> code = compile("""class K: pass""", '', 'exec')
>>> dis.dis(code)
  1           0 LOAD_CONST               0 ('K')
              3 LOAD_CONST               3 (())
              6 LOAD_CONST               1 (<code object K at 0xb7e8ad10,
file "", line 1>)
              9 MAKE_FUNCTION            0
             12 CALL_FUNCTION            0
             15 BUILD_CLASS
             16 STORE_NAME               0 (K)
             19 LOAD_CONST               2 (None)
             22 RETURN_VALUE

So a code object is compiled, turned into a function, executed, the results
turned into a class, and the code object and function thrown away.

Is this an implementation detail? I would say so. The semantics of Python
the language are different from the details of it's virtual machine. Surely
we would be allowed to call something Python if it executed the body of the
class statement *without* creating a code object first? The important part
is *execute the body of the class statement*, not building the code object.
The later is merely a means to an end.

> So the use of code objects for execution is an implementation detail.
> Instead of "code object" I should have referred to the code executed
> in the execution frame or just to the frame.

Unless you really intend to talk about implementation details, I think you
should keep the discussion as high-level as possible. I'd talk about
executing blocks of code, and not even mention execution frames unless you
need to understand the role of frames during execution.


More information about the Python-list mailing list