sys PyFrameObject 实现

sys.settrace 为built-in函数

底层实现代码

  1. https://github.com/python/cpython/blob/master/Python/sysmodule.c
  2. https://github.com/python/cpython/blob/master/Python/ceval.c

PyFrameObject 实现

  1. https://github.com/python/cpython/blob/master/Include/frameobject.h
  2. https://github.com/python/cpython/blob/master/Objects/frameobject.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import sys


def trace_func(frame, event, arg):
value = frame.f_locals["a"]
if value % 2 == 0:
value += 1
frame.f_locals["a"] = value


def f(a):
print(a)


if __name__ == "__main__":
trace = sys.gettrace()
sys.settrace(trace_func)
for i in range(0, 5):
f(i)
sys.settrace(trace)