How does CPython work
Disconnect3d
PyCon PL 2018, 24.08.2018
1
CPython
“The reference implementation”
CPython
“The reference implementation”
CPython
“The reference implementation”
There are others: PyPy, Cython, JPython, IronPython, etc
“Is Python interpreted or compiled?”
“Yes.”
https://nedbatchelder.com/blog/201803/is_python_interpreted_or_compiled_yes.html
“Is Python interpreted or compiled?”
“Yes.”
https://nedbatchelder.com/blog/201803/is_python_interpreted_or_compiled_yes.html
The flow
script.py
The flow
script.py bytecode (pyc)
The flow
script.py bytecode (pyc) run by CPython VM
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
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
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
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
CPython VM
The idea
for (;;) {
switch (get_opcode()) {
case LOAD_GLOBAL: ...
case LOAD_CONST: ...
case CALL_FUNCTION: ...
...
}
}
The code
#define TARGET(op) \
TARGET_##op: \
case op:
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”
The code
The end