[Tutor] PyMOTW: difflib

Alan Gauld alan.gauld at btinternet.com
Tue Apr 8 01:52:25 CEST 2008


"Dick Moores" <rdm at rcblue.com> wrote 

> Could you give a blow-by-blow on the dis.dis()?

I'll have a go but I've never actually studied Python P-Code, 
this is based on my 8080 and 68000 assembler experience!

> In [22]: def f(x):
>   ....:     if x%2:
>   ....:         return "odd"
>   ....:     else:
>   ....:         return "even"
>   ....:
>   ....:
> 
> In [23]: dis.dis(f)
>  2           0 LOAD_FAST                0 (x)
>              3 LOAD_CONST               1 (2)

load x and 2 into two temporary storage areas
(registers in conventional assembler)

>              6 BINARY_MODULO

Do the modulo operation and store the result in a temporary 
location (accumulator in assembler)

>              7 JUMP_IF_FALSE            8 (to 18)

If the result is zero(false) go to instruction 18 
(I don't know what the 8 signifies, I thought a
program counter offset but that would make it 
a jump to 15...)

>             10 POP_TOP

else (ie modulo result is non zero) pop the top - I'm 
not sure what that does exactly but I assume it pops 
a value of some stack into the accumulator area?

>  3          11 LOAD_CONST               2 ('odd')
>             14 RETURN_VALUE

Load 'odd' into storage area 2 and then return it?

>             15 JUMP_FORWARD             5 (to 23)

Not sure about this bit...

>        >>   18 POP_TOP

This was target of our previous jump if false instruiction

>  5          19 LOAD_CONST               3 ('even')
>             22 RETURN_VALUE

So it loads 'even' and then returns it to the caller.

>        >>   23 LOAD_CONST               0 (None)
>             26 RETURN_VALUE

I assume this is the default return value in case there is no 
other returns, so not used here.

I'm no expert but I'm sure someone else can fix up my errors 
but its very like any other kind of assembler - you just need 
to look up the behaviour of each op code.

Alan G.



More information about the Tutor mailing list