[Tutor] bytecode primer, and avoiding a monster download

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue May 28 19:58:05 CEST 2013


On 28 May 2013 18:24, eryksun <eryksun at gmail.com> wrote:
> On Tue, May 28, 2013 at 1:12 PM, Oscar Benjamin
> <oscar.j.benjamin at gmail.com> wrote:
>> On 28 May 2013 17:48, eryksun <eryksun at gmail.com> wrote:
>>>
>>> The argument for dis.dis() can be a module, class, function or code
>>> object. It disassembles all the top-level code objects that it finds,
>>> but it doesn't recursively disassemble code objects that are in the
>>> co_consts.
>>
>> What do you mean by this? I tried passing a test module into dis.dis
>> and nothing happens:
>
> Obviously dis() has nothing to do if the module or class namespace has
> no code objects to disassemble.
>
> Did you read the rest of my post?

Yes. Although I'll admit that I didn't fully absorb all of it. :)

> I went through an example of loading
> the cached code object from a .pyc. But we can just compile one
> instead:

Okay, got you. So the way to dis an ordinary module is to load the .py
file as a string first:

>>> dis.dis(compile(open('tmp.py').read(), 'tmp', 'exec'))
  2           0 LOAD_CONST               0 (1)
              3 STORE_NAME               0 (a)

  3           6 LOAD_CONST               1 (2)
              9 STORE_NAME               1 (b)

  4          12 LOAD_NAME                0 (a)
             15 LOAD_NAME                1 (b)
             18 BINARY_ADD
             19 STORE_NAME               2 (c)
             22 LOAD_CONST               2 (None)
             25 RETURN_VALUE

So what happens to the code object for the top-level code in the
module itself when it is imported in the normal way? Is it just
discarded once import is complete? Is it temporarily accessible during
import?


Oscar


More information about the Tutor mailing list