[Tutor] bytecode primer, and avoiding a monster download
eryksun
eryksun at gmail.com
Tue May 28 19:24:42 CEST 2013
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.
>>>> import tmp
>>>> tmp.a
> 1
>>>> import dis
>>>> dis.dis(tmp)
>>>> print(dis.dis(tmp))
> None
>
> This module contains no functions but it does contain lines of code
> and the interpreter will turn those into bytecode somewhere. I think
> that's what Dave meant.
Did you read the rest of my post? I went through an example of loading
the cached code object from a .pyc. But we can just compile one
instead:
>>> code = compile(r'''
... 'module docstring'
... class Test(object):
... 'class docstring'
... def spam(self):
... pass
... ''', '<test>', 'exec')
>>> dis.dis(code)
2 0 LOAD_CONST 0 ('module docstring')
3 STORE_NAME 0 (__doc__)
3 6 LOAD_CONST 1 ('Test')
9 LOAD_NAME 1 (object)
12 BUILD_TUPLE 1
15 LOAD_CONST 2 (<code object Test....>)
18 MAKE_FUNCTION 0
21 CALL_FUNCTION 0
24 BUILD_CLASS
25 STORE_NAME 2 (Test)
28 LOAD_CONST 3 (None)
31 RETURN_VALUE
>>> dis.dis(code.co_consts[2])
3 0 LOAD_NAME 0 (__name__)
3 STORE_NAME 1 (__module__)
4 6 LOAD_CONST 0 ('class docstring')
9 STORE_NAME 2 (__doc__)
5 12 LOAD_CONST 1 (<code object spam....>)
15 MAKE_FUNCTION 0
18 STORE_NAME 3 (spam)
21 LOAD_LOCALS
22 RETURN_VALUE
Let's exec this in a new module and run dis() on it:
>>> testmod = imp.new_module('testmod')
>>> exec code in vars(testmod)
>>> dis.dis(testmod)
Disassembly of Test:
Disassembly of spam:
6 0 LOAD_CONST 0 (None)
3 RETURN_VALUE
Admittedly it's not very interesting since spam() does nothing.
More information about the Tutor
mailing list