Dive into CPython Bytecode

download Dive into CPython Bytecode

If you can't read please download the document

Transcript of Dive into CPython Bytecode

Dive into CPython Bytecode

Dive into CPython Bytecode

Alex Gaynor

I don't need to know that stuff

You don't. But it's totally helpful.

How does CPython Make Bytecode?

Tokenize the source

Parse the tokens into an AST

Build a symbol table to figure out what's a global

Compile to bytecode

Now I can haz bytecode

Now that I has a bytecode how does I see it?

>>> def f(o):... return o

>>> import dis>>> dis.dis(f) 2 0 LOAD_FAST 0 (o) 3 RETURN_VALUE

So use the dis module

So now that we have bytecode, what do we do with it?

Well, what are those bytecodes?

A few examples

UNARY_NEGATIVE: -TOS

BINARY_ADD: TOS1 + TOS

SLICE+3: TOS2[TOS1:TOS]

UNPACK_SEQUENCE

LOAD_CONST

CALL_FUNCTION_VAR_KW

Python VM is stack based

So now we know some bytecodes, what can we do with this knowledge

A tale of 2 functions

>>> def f():

... return [x for x in xrange(10)]

>>> def g():

... o = []

... for x in xrange(10):

... o.append(x)

... return o

Less Bytecode == faster!

More specialized bytecodes == faster

@alex_gaynor

Thanks

09/10/09

09/10/09