MCPcopy Index your code
hub / github.com/python/cpython / generate_trace

Function generate_trace

Doc/tools/extensions/profiling_trace.py:41–120  ·  view source on GitHub ↗

Execute the source code with tracing enabled and capture execution events.

(source: str)

Source from the content-addressed store, hash-verified

39
40
41def generate_trace(source: str) -> list[dict]:
42 """
43 Execute the source code with tracing enabled and capture execution events.
44 """
45 trace_events = []
46 timestamp = [0]
47 timestamp_step = 50
48 tracing_active = [False]
49 pending_line = [None]
50
51 def tracer(frame, event, arg):
52 if frame.f_code.co_filename != '<demo>':
53 return tracer
54
55 func_name = frame.f_code.co_name
56 lineno = frame.f_lineno
57
58 if event == 'line' and not tracing_active[0]:
59 pending_line[0] = {'type': 'line', 'line': lineno}
60 return tracer
61
62 # Start tracing only once main() is called
63 if event == 'call' and func_name == 'main':
64 tracing_active[0] = True
65 # Emit the buffered line event (the main() call line) at ts=0
66 if pending_line[0]:
67 pending_line[0]['ts'] = 0
68 trace_events.append(pending_line[0])
69 pending_line[0] = None
70 timestamp[0] = timestamp_step
71
72 # Skip events until we've entered main()
73 if not tracing_active[0]:
74 return tracer
75
76 if event == 'call':
77 trace_events.append({
78 'type': 'call',
79 'func': func_name,
80 'line': lineno,
81 'ts': timestamp[0],
82 })
83 elif event == 'line':
84 trace_events.append({
85 'type': 'line',
86 'line': lineno,
87 'ts': timestamp[0],
88 })
89 elif event == 'return':
90 try:
91 value = arg if arg is None else repr(arg)
92 except Exception:
93 value = '<unprintable>'
94 trace_events.append({
95 'type': 'return',
96 'func': func_name,
97 'ts': timestamp[0],
98 'value': value,

Callers 1

inject_traceFunction · 0.85

Calls 2

StringIOClass · 0.90
compileFunction · 0.50

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…