1 of 19

How does CPython work

Disconnect3d

PyCon PL 2018, 24.08.2018

1

2 of 19

CPython

“The reference implementation”

3 of 19

CPython

“The reference implementation”

4 of 19

CPython

“The reference implementation”

There are others: PyPy, Cython, JPython, IronPython, etc

5 of 19

“Is Python interpreted or compiled?”

“Yes.”

https://nedbatchelder.com/blog/201803/is_python_interpreted_or_compiled_yes.html

6 of 19

“Is Python interpreted or compiled?”

“Yes.”

https://nedbatchelder.com/blog/201803/is_python_interpreted_or_compiled_yes.html

7 of 19

The flow

script.py

8 of 19

The flow

script.py bytecode (pyc)

9 of 19

The flow

script.py bytecode (pyc) run by CPython VM

10 of 19

Bytecode consists of opcodes

def foo(x):print('Hello world')�� y = x ** 2�� return y

dis.dis(foo)

2 0 LOAD_GLOBAL 0 (print)

2 LOAD_CONST 1 ('Hello world')

4 CALL_FUNCTION 1

6 POP_TOP

4 8 LOAD_FAST 0 (x)

10 LOAD_CONST 2 (2)

12 BINARY_POWER

14 STORE_FAST 1 (y)

6 16 LOAD_FAST 1 (y)

18 RETURN_VALUE

11 of 19

Bytecode consists of opcodes

def foo(x):print('Hello world')�� y = x ** 2�� return y

dis.dis(foo)

2 0 LOAD_GLOBAL 0 (print)

2 LOAD_CONST 1 ('Hello world')

4 CALL_FUNCTION 1

6 POP_TOP

4 8 LOAD_FAST 0 (x)

10 LOAD_CONST 2 (2)

12 BINARY_POWER

14 STORE_FAST 1 (y)

6 16 LOAD_FAST 1 (y)

18 RETURN_VALUE

12 of 19

Bytecode consists of opcodes

def foo(x):print('Hello world')�� y = x ** 2�� return y

dis.dis(foo)

2 0 LOAD_GLOBAL 0 (print)

2 LOAD_CONST 1 ('Hello world')

4 CALL_FUNCTION 1

6 POP_TOP

4 8 LOAD_FAST 0 (x)

10 LOAD_CONST 2 (2)

12 BINARY_POWER

14 STORE_FAST 1 (y)

6 16 LOAD_FAST 1 (y)

18 RETURN_VALUE

13 of 19

Bytecode consists of opcodes

def foo(x):print('Hello world')�� y = x ** 2�� return y

dis.dis(foo)

2 0 LOAD_GLOBAL 0 (print)

2 LOAD_CONST 1 ('Hello world')

4 CALL_FUNCTION 1

6 POP_TOP

4 8 LOAD_FAST 0 (x)

10 LOAD_CONST 2 (2)

12 BINARY_POWER

14 STORE_FAST 1 (y)

6 16 LOAD_FAST 1 (y)

18 RETURN_VALUE

14 of 19

CPython VM

15 of 19

The idea

for (;;) {

switch (get_opcode()) {

case LOAD_GLOBAL: ...

case LOAD_CONST: ...

case CALL_FUNCTION: ...

...

}

}

16 of 19

The code

#define TARGET(op) \

TARGET_##op: \

case op:

17 of 19

The code

#define TARGET(op) \

TARGET_##op: \

case op:

https://eli.thegreenplace.net/2012/07/12/computed-goto-for-efficient-dispatch-tables

This is for “computed gotos”

18 of 19

The code

19 of 19

The end

Hope you enjoyed o/

https://disconnect3d.pl/

disconnect3d # irc.freenode.net