iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🔍

Monitoring Python Code Execution: Building Custom Coverage and Call Graphs

に公開

Introduction

Python 3.12 added sys.monitoring.
This makes it possible to monitor start events and RETURN events for code objects.

By applying this feature, you can create your own coverage measurement and call graphs.
This article will investigate and experiment with how to use this library.
Also, since we use code objects, it is assumed that you have at least a basic knowledge of bytecode.

Simple Example

Below is a sample code for monitoring the call of a specific function and its return value events.

Sample Code

from sys import monitoring
from types import CodeType
import dis

def func_x(n):
    a = func_y(n)
    return a * 2

def func_y(n):
    return 5

def show_code(code):
    for ins in dis.Bytecode(code):
        line_no = "   "
        if ins.line_number:
            line_no = f"{ins.line_number:3}"
        print(f"  {line_no} {ins.offset:3}: {ins.baseopname} {ins.argval}")

print("Bytecode of func_x-----")
show_code(func_x)
print("Bytecode of func_y-----")
show_code(func_y)


events = monitoring.events
tool_id = monitoring.DEBUGGER_ID

# Must be called before using tool_id. tool_id must be in range 0 to 5.
monitoring.use_tool_id(monitoring.DEBUGGER_ID, "SimpleMonitor")

def on_py_start(code: CodeType, offset: int):
    # Event at the start of a Python function (occurs immediately after call, caller's frame is on the stack)
    print(f"[on_py_start] {code.co_name} offset:{offset}")

def on_py_return(code: CodeType, offset: int, retval: object):
    # Return from a Python function (occurs just before return, caller's frame is on the stack)
    print(f"[on_return]  {code.co_name} -> {retval!r}({type(retval)}) offset:{offset}")

def on_call(caller_code: CodeType, offset:int, callee_obj: object, arg0: object):
    # Call within Python code (event occurs before the call)
    # arg0 holds the first argument. (Other arguments cannot be observed)
    print(f"[on_call] {caller_code.co_name} -> {callee_obj!r} offset:{offset} arg0:{arg0!r}")

# 
monitoring.register_callback(tool_id, events.PY_START, on_py_start)
monitoring.register_callback(tool_id, events.PY_RETURN, on_py_return)
monitoring.register_callback(tool_id, events.CALL, on_call)

target_events = (
    events.PY_START |
    events.PY_RETURN |
    events.CALL
)

# Only get events for a specific CodeType
print('=====func_x after set_local_events')
monitoring.set_local_events(tool_id, func_x.__code__, target_events)
func_x(100)

# Unregister events
monitoring.register_callback(tool_id, events.PY_START, None)
monitoring.register_callback(tool_id, events.PY_RETURN, None)
monitoring.register_callback(tool_id, events.CALL, None)
monitoring.free_tool_id(tool_id)

Example Output:

Bytecode of func_x-----
    5   0: RESUME 0
    6   2: LOAD_GLOBAL func_y
    6  12: LOAD_FAST n
    6  14: CALL 1
    6  22: STORE_FAST a
    7  24: LOAD_FAST a
    7  26: LOAD_CONST 2
    7  28: BINARY_OP 5
    7  32: RETURN_VALUE None
Bytecode of func_y-----
    9   0: RESUME 0
   10   2: RETURN_CONST 5
=====func_x after set_local_events
[on_py_start] func_x offset:0
[on_call] func_x -> <function func_y at 0x105523740> offset:14 arg0:100
[on_return]  func_x -> 10(<class 'int'>) offset:32

Explanation of the Simple Sample Code

The steps to monitor events like specific function calls are as follows:

  1. Declare the use of an event ID using use_tool_id
  2. Bind events and their callback functions using register_callback
  3. Enable event monitoring using set_local_events or set_events
  4. Execute the target function
  5. Clean up monitoring

Declare the use of an event ID using use_tool_id

Events such as specific function calls can be monitored per tool ID. The following IDs are pre-assigned, allowing collaboration between tools:

sys.monitoring.DEBUGGER_ID = 0
sys.monitoring.COVERAGE_ID = 1
sys.monitoring.PROFILER_ID = 2
sys.monitoring.OPTIMIZER_ID = 5

Before monitoring any events, you must first declare the use of the event ID using use_tool_id.

Bind events and their callback functions using register_callback

Next, use register_callback to bind events and their callback functions.

This time we will monitor the following events:

For the callback function arguments, refer to Callback function arguments.

PY_START

This event occurs at the start of a Python function, immediately after the function begins.
Write a callback function like the following:

def on_py_start(code: CodeType, offset: int):
    # Event at the start of a Python function (occurs immediately after call, caller's frame is on the stack)
    print(f"[on_py_start] {code.co_name} offset:{offset}")

The call stack immediately after this callback is called is as follows:

on_py_start   <- currently executing (topmost)
  func_x      <- about to start execution (just before RESUME)
    caller    <- function that called func_x

code is the CodeType of the function that was started.

offset indicates the bytecode offset of the target code at which the event fired.

In this case, it appears as offset:0 as shown below:

[on_py_start] func_x offset:0

This corresponds to line 5 of func_x's bytecode, offset 0, which is the position of RESUME 0.

PY_RETURN

This event occurs just before returning from a Python function.
Write a callback function like the following:

def on_py_return(code: CodeType, offset: int, retval: object):
    # Return from a Python function (occurs just before return, caller's frame is on the stack)
    print(f"[on_return]  {code.co_name} -> {retval!r}({type(retval)}) offset:{offset}")

code is the CodeType of the function performing the return.

offset indicates the bytecode offset of the target code at which the event fired.
In this case, it appears as offset:32 as shown below:

[on_return]  func_x -> 10(<class 'int'>) offset:32

This corresponds to line 7 of func_x's bytecode, offset 32, which is the position of RETURN_VALUE.

CALL

This event occurs just before a CALL in bytecode is invoked.
Write a callback function like the following:

def on_call(caller_code: CodeType, offset:int, callee_obj: object, arg0: object):
    # Call within Python code (event occurs before the call)
    # arg0 holds the first argument. (Other arguments cannot be observed)
    print(f"[on_call] {caller_code.co_name} -> {callee_obj!r} offset:{offset} arg0:{arg0!r}")

caller_code is the CodeType of the function making the call.

offset is the offset value where CALL is executed.
In this case, the output is as follows:

[on_call] func_x -> <function func_y at 0x105523740> offset:14 arg0:100

We can confirm that offset:14 in func_x's bytecode is CALL 1.

callee_obj is the function or method being called.

arg0 is the first argument. If there are multiple, only one can be observed. If there are no arguments, it is sys.monitoring.MISSING.

Enable event monitoring using set_local_events or set_events

set_local_events can monitor events occurring in a specific function.

target_events = (
    events.PY_START |
    events.PY_RETURN |
    events.CALL
)
monitoring.set_local_events(tool_id, func_x.__code__, target_events)

In this case, we are only monitoring func_x, so the monitoring results are as follows:

[on_py_start] func_x offset:0
[on_call] func_x -> <function func_y at 0x105523740> offset:14 arg0:100
[on_return]  func_x -> 10(<class 'int'>) offset:32

We can confirm that only events from func_x are being monitored.

If you use set_events, all functions become targets.

monitoring.set_events(tool_id, target_events)
func_x(100)

In this case, the output is as follows:

=====func_x after set_local_events
[on_call] <module> -> <function func_x at 0x10e465ee0> offset:604 arg0:100
[on_py_start] func_x offset:0
[on_call] func_x -> <function func_y at 0x10e51f740> offset:14 arg0:100
[on_py_start] func_y offset:0
[on_return]  func_y -> 5(<class 'int'>) offset:2
[on_return]  func_x -> 10(<class 'int'>) offset:32
[on_call] <module> -> <built-in function register_callback> offset:664 arg0:0

Since the entire process is being monitored, behaviors like unregistering events with register_callback and print are also monitored, so appropriate filtering is needed on the callback function side.

Clean Up Monitoring

For Python 3.13 and earlier, you need to unregister the callbacks and then call free_tool_id as follows:

# Unregister events
monitoring.register_callback(tool_id, events.PY_START, None)
monitoring.register_callback(tool_id, events.PY_RETURN, None)
monitoring.register_callback(tool_id, events.CALL, None)
monitoring.free_tool_id(tool_id)

Since Python 3.14, the behavior of free_tool_id has changed, so you do not need to unregister callbacks with register_callback.

For example, suppose you run the monitored function again with some callbacks left unregistered:

monitoring.register_callback(tool_id, events.PY_START, None)
# monitoring.register_callback(tool_id, events.PY_RETURN, None)
# monitoring.register_callback(tool_id, events.CALL, None)
monitoring.free_tool_id(tool_id)
print('===== func_x after free_tool_id')
func_x(100)

In Python 3.13, the callbacks will still fire as follows:

===== func_x after free_tool_id
[on_call] func_x -> <function func_y at 0x109523740> offset:14 arg0:100
[on_return]  func_x -> 10(<class 'int'>) offset:32

However, in Python 3.14, free_tool_id internally calls clear_tool_id to clean up event registrations, so the callbacks will no longer fire:

===== func_x after free_tool_id

Complex Examples

Call Graph + Line Coverage Example

The following example performs these monitoring tasks:

  • Build a call graph by watching function call targets
  • Collect line coverage within functions
  • Collect return values within functions
  • Collect yield values within functions
  • Collect function call arguments
  • Collect exceptions within functions
Class for building call graphs

Class for building call graphs

import threading
import sys
import asyncio
import os
from inspect import ArgInfo, getargvalues
from sys import monitoring
from types import CodeType, FunctionType, BuiltinFunctionType, MethodType
from typing import Optional
from dataclasses import dataclass, field

events = monitoring.events

def _unwrap_func(obj):
    if isinstance(obj, classmethod) or isinstance(obj, staticmethod):
        return obj.__func__
    if isinstance(obj, (FunctionType, BuiltinFunctionType)):
        return obj
    if isinstance(obj, MethodType):
        return obj.__func__
    return None

@dataclass
class CallNode:
    code: CodeType
    call_count: int
    calls: set['CallNode'] = field(default_factory=set)
    exceptions: list[BaseException] = field(default_factory=list)
    arg_infos: list[ArgInfo] = field(default_factory=list)
    cover_lines: set[int] = field(default_factory=set)
    returns: list[object] = field(default_factory=list)
    yields: list[object] = field(default_factory=list)
    def __hash__(self) -> int:
        return hash(self.code)

class NestFunctionMonitor:
    def __init__(self, root_folder: str):
        self.tool_id = monitoring.DEBUGGER_ID
        monitoring.use_tool_id(monitoring.DEBUGGER_ID, "NestFunctionMonitor")
        self.local_events = (
            events.PY_RETURN |
            events.PY_YIELD |
            events.LINE
        )
        self.global_events = (
            events.PY_START |
            events.RAISE
        )
        self.lock = threading.Lock()
        self.ignore_codes = self._collect_own_codes()
        self.dict_nodes: dict[CodeType, CallNode] = {}
        self.max_sample = 10
        self.abs_root_folder = os.path.abspath(root_folder)

    def _collect_own_codes(self):
        codes = set()
        # Collect all functions defined in this class (include inherited by traversing __mro__)
        for cls in type(self).__mro__:    # Break on object if needed
            if cls is object:
                break
            for _, obj in cls.__dict__.items():
                f = _unwrap_func(obj)
                if f and getattr(f, "__code__", None):
                    codes.add(f.__code__)
        # Collect dynamically added attributes on the instance (if necessary)
        for v in self.__dict__.values():
            f = _unwrap_func(v)
            if f and getattr(f, "__code__", None):
                codes.add(f.__code__)
        return codes

    def start(self):
        monitoring.register_callback(self.tool_id, events.PY_START, self.on_py_start)
        monitoring.register_callback(self.tool_id, events.RAISE, self.on_raise)
        monitoring.register_callback(self.tool_id, events.PY_RETURN, self.on_py_return)
        monitoring.register_callback(self.tool_id, events.PY_YIELD, self.on_py_yield)
        monitoring.register_callback(self.tool_id, events.LINE, self.on_line)
        monitoring.set_events(self.tool_id, self.global_events)

    def stop(self):
        monitoring.register_callback(self.tool_id, events.PY_START, None)
        monitoring.register_callback(self.tool_id, events.RAISE, None)
        monitoring.register_callback(self.tool_id, events.PY_RETURN, None)
        monitoring.register_callback(self.tool_id, events.PY_YIELD, None)
        monitoring.register_callback(self.tool_id, events.LINE, None)
        monitoring.free_tool_id(self.tool_id)

    def __enter__(self):
        self.start()
        return self

    def __exit__(self, exc_type, exc, tb):
        self.stop()

    def on_py_start(self, code: CodeType, instruction_offset: int):
        if code in self.ignore_codes:
            return monitoring.DISABLE
        if not code.co_filename.startswith(self.abs_root_folder):
            return monitoring.DISABLE
        tid = threading.get_ident()
        cur = sys._current_frames()[tid]
        print(f"[on_py_start] {tid} {code.co_qualname} {code.co_filename} instruction_offset:{instruction_offset}")
        with self.lock:
            node = self.dict_nodes.get(code)
            if not node:
                node = CallNode(code, 0, set())
                self.dict_nodes[code] = node
                monitoring.set_local_events(self.tool_id, code, self.local_events)
            node.call_count += 1
            start_watch = False
            while cur:
                if start_watch and self.dict_nodes.get(cur.f_code):
                    self.dict_nodes.get(cur.f_code).calls.add(node)
                    if len(node.arg_infos) <= self.max_sample:
                        args_info = getargvalues(cur)
                        node.arg_infos.append(args_info)
                    break
                elif code is cur.f_code:
                    start_watch = True
                cur = cur.f_back

    def on_raise(self, code: CodeType, instruction_offset: int, exception: BaseException):
        # Occurs when an exception is raised, excluding cases caused by StopIteration signaling iteration end
        print(f'[on_raise] {threading.get_ident()} {code.co_name} {instruction_offset} {exception}')
        with self.lock:
            node = self.dict_nodes.get(code)
            if node and len(node.exceptions) <= self.max_sample:
                node.exceptions.append(exception)

    def on_py_return(self, code, offset, retval):
        print(f"[on_return]  {code.co_name} -> {retval!r}({type(retval)}) offset:{offset}")
        node = self.dict_nodes.get(code)
        if node and len(node.returns) <= self.max_sample:
            node.returns.append(retval)

    def on_py_yield(self, code, offset, retval):
        print(f"[on_py_yield]  {code.co_name} -> {retval!r}({type(retval)}) offset:{offset}")
        node = self.dict_nodes.get(code)
        if node and len(node.yields) <= self.max_sample:
            node.yields.append(retval)

    def on_line(self, code: CodeType, line_number: int):
        print(f'[on_line] {code.co_name} line_no:{line_number}')
        node = self.dict_nodes.get(code)
        if node:
            node.cover_lines.add(line_number)

    def dump(self):
        self.stop()

        roots = []
        for _, node1 in self.dict_nodes.items():
            has_parent = False
            for node2 in self.dict_nodes.values():
                if node1 is node2:
                    continue
                if node1 in node2.calls:
                    has_parent = True
                    break
            if not has_parent:
                roots.append(node1)
        for node in roots:
            self.dump_node(node)
    
    def dump_node(self, node: CallNode, route_path: Optional[list[CallNode]] = None):
        depth = 0
        if route_path:
            depth = len(route_path)
        else:
            route_path = []
        route_path.append(node)
        print(f"{' '*depth}{node.code.co_qualname} (execution count:{node.call_count})")
        print(f"{' '*(depth+2)} argument samples: {node.arg_infos}")
        print(f"{' '*(depth+2)} exception samples: {node.exceptions}")
        print(f"{' '*(depth+2)} return value samples: {node.returns}")
        print(f"{' '*(depth+2)} yield samples: {node.yields}")
        print(f"{' '*(depth+2)} executed lines: {node.cover_lines}")
        for child in node.calls:
            if child in route_path:
                # Circular call
                continue
            self.dump_node(child, route_path)

Explanation
The monitoring approach is to monitor global PY_START and RAISE events.
When monitoring global events, filtering is applied based on the following conditions:

  • The code must be located under the specified root folder.
  • The code must not belong to NestFunctionMonitor's own methods.
    Then, within the PY_START event, we monitor PY_RETURN, PY_YIELD, and LINE events for that function.
    To support multi-threaded environments, we use a lock when operating shared objects accessed from callback functions.

Normal Function Call Example

When no exception occurs, the function call result is as follows:

def test_1(s:int, n: int)->int:
    try:
        return test_2(s) * n
    except ValueError:
        return -1

def test_2(s)->int:
    return test_3(s)

def test_3(s)->int:
    if s % 2 == 0:
        return s * 2
    else:
        raise ValueError("exception")

with NestFunctionMonitor("./src") as mon:
    test_1(2, 1)

The output below shows the call tree relationship of each function, along with observed arguments and return values.

test_1 (execution count:1)
   argument samples: []
   exception samples: []
   return value samples: [4]
   yield samples: []
   executed lines: {185, 186}
 test_2 (execution count:1)
    argument samples: [ArgInfo(args=['s', 'n'], varargs=None, keywords=None, locals={'s': 2, 'n': 1})]
    exception samples: []
    return value samples: [4]
   yield samples: []
    executed lines: {191}
  test_3 (execution count:1)
     argument samples: [ArgInfo(args=['s'], varargs=None, keywords=None, locals={'s': 2})]
     exception samples: []
     return value samples: [4]
    yield samples: []
     executed lines: {194, 195}

If we observe a function where an exception occurs, we can see that exceptions are detected in test_1, test_2, and test_3, and that RETURN does not occur in test_2 and test_3 because they do not handle the exception.

with NestFunctionMonitor("./src") as mon:
    test_1(1, 1)
    mon.dump()
test_1 (execution count:1)
   argument samples: []
   exception samples: [ValueError('exception')]
   return value samples: [-1]
   yield samples: []
   executed lines: {185, 186, 187, 188}
 test_2 (execution count:1)
    argument samples: [ArgInfo(args=['s', 'n'], varargs=None, keywords=None, locals={'s': 1, 'n': 1})]
    exception samples: [ValueError('exception')]
    return value samples: []
   yield samples: []
    executed lines: {191}
  test_3 (execution count:1)
     argument samples: [ArgInfo(args=['s'], varargs=None, keywords=None, locals={'s': 1})]
     exception samples: [ValueError('exception')]
     return value samples: []
    yield samples: []
     executed lines: {194, 197}

Generator Usage Example

Let's check an example of observing a function that uses generators.

def yield_sample(n, d):
    for i in range(n):
        yield i * d

def yield_from_sample():
    yield from yield_sample(2, 2)
    yield from yield_sample(10, 3)

with NestFunctionMonitor("./src") as mon:
    for n in yield_from_sample():
        print(n)
    mon.dump()

In this example, we can confirm that yields occur in yield_sample and yield_from_sample.

yield_from_sample (execution count:1)
   argument samples: []
   exception samples: []
   return value samples: [None]
   yield samples: [0, 2, 0, 3, 6, 9, 12, 15, 18, 21, 24]
   executed lines: {204, 205}
 yield_sample (execution count:2)
    argument samples: [ArgInfo(args=[], varargs=None, keywords=None, locals={}), ArgInfo(args=[], varargs=None, keywords=None, locals={})]
    exception samples: []
    return value samples: [None, None]
   yield samples: [0, 2, 0, 3, 6, 9, 12, 15, 18, 21, 24]
    executed lines: {200, 201}

Asynchronous Function Usage Example

Let's check an example using asynchronous functions.

async def async_test(name: str, n: float):
    print("start...", name)
    await asyncio.sleep(n)
    print("end...", name)
    return f"{name}:{n}"

async def async_main():
    res1 = await async_test("1st", 0.02)
    res2 = await async_test("2nd", 0.01)
    res3 = await async_test("3rd", 0.01)
    print(res1)
    print(res2)
    print(res3)

with NestFunctionMonitor("./src") as mon:
    with asyncio.Runner(debug=True) as runner:
        runner.run(async_main())
    mon.dump()

We can observe the return values of async_test and also see that Future objects are being yielded.

async_main (execution count:1)
   argument samples: []
   exception samples: []
   return value samples: [None]
   yield samples: [<Future finished result=None created at /Users/user/.pyenv/versions/3.14.0/lib/python3.14/asyncio/base_events.py:459>, <Future finished result=None created at /Users/user/.pyenv/versions/3.14.0/lib/python3.14/asyncio/base_events.py:459>, <Future finished result=None created at /Users/user/.pyenv/versions/3.14.0/lib/python3.14/asyncio/base_events.py:459>]
   executed lines: {224, 225, 226, 227, 228, 223}
 async_test (execution count:3)
    argument samples: [ArgInfo(args=[], varargs=None, keywords=None, locals={'res1': '1st:0.02', 'res2': '2nd:0.01', 'res3': '3rd:0.01'}), ArgInfo(args=[], varargs=None, keywords=None, locals={'res1': '1st:0.02', 'res2': '2nd:0.01', 'res3': '3rd:0.01'}), ArgInfo(args=[], varargs=None, keywords=None, locals={'res1': '1st:0.02', 'res2': '2nd:0.01', 'res3': '3rd:0.01'})]
    exception samples: []
    return value samples: ['1st:0.02', '2nd:0.01', '3rd:0.01']
   yield samples: [<Future finished result=None created at /Users/user/.pyenv/versions/3.14.0/lib/python3.14/asyncio/base_events.py:459>, <Future finished result=None created at /Users/user/.pyenv/versions/3.14.0/lib/python3.14/asyncio/base_events.py:459>, <Future finished result=None created at /Users/user/.pyenv/versions/3.14.0/lib/python3.14/asyncio/base_events.py:459>]
    executed lines: {216, 217, 218, 219}

Bytecode Coverage Example

The following example demonstrates collecting bytecode-level coverage.

  • Collect coverage at the bytecode level.
  • Maintain the execution order of instructions.
    • This manages execution order per thread.
Class for building bytecode coverage
import dis
from types import CodeType
from sys import monitoring
import threading
from concurrent.futures import ThreadPoolExecutor

events = monitoring.events

class ByteCodeMonitor:
    def __init__(self, code: CodeType):
        self.target_code = code
        self.tool_id = monitoring.DEBUGGER_ID
        self.watch_events = events.INSTRUCTION
        self.lock = threading.Lock()
        self.thread_steps = {}
        monitoring.use_tool_id(monitoring.DEBUGGER_ID, "ByteCodeMonitor")

    def start(self):
        monitoring.register_callback(self.tool_id, events.INSTRUCTION, self.on_instruction)
        monitoring.set_local_events(self.tool_id, self.target_code, self.watch_events)

    def stop(self):
        monitoring.register_callback(self.tool_id, events.INSTRUCTION, None)
        monitoring.free_tool_id(self.tool_id)

    def __enter__(self):
        self.start()
        return self

    def __exit__(self, exc_type, exc, tb):
        self.stop()

    def on_instruction(self, code: CodeType, instruction_offset: int):
        # The VM instruction is about to be executed
        tid = threading.get_ident()
        with self.lock:
            if tid not in self.thread_steps:
                self.thread_steps[tid] = []
            self.thread_steps[tid].append(instruction_offset)
            print(f'[on_instruction] ({tid}):({len(self.thread_steps[tid])}) {code.co_name} instruction_offset: {instruction_offset}')

    def show_dump(self):
        for tid, steps in self.thread_steps.items():
            print(f'{tid}=============')
            for ins in dis.Bytecode(self.target_code):
                indexes = [f"{i + 1:3}" for i, step in enumerate(steps) if step == ins.offset]
                line_no = "   "
                if ins.line_number:
                    line_no = f"{ins.line_number:3}"
                print(f"  {line_no} {ins.offset:3}: {ins.baseopname.ljust(36)} {str(ins.argval).ljust(16)}    ... {indexes[:10]}")

This example monitors the INSTRUCTION event, which occurs when a VM instruction is about to be executed.
The order of occurrences is monitored per thread.

Let's observe the bytecode coverage.

def sum_even_double(nums: list[int]) -> int:
    total = 0
    for n in nums:
        if n % 2 == 0:
            total += n * 2
    return total

with ByteCodeMonitor(sum_even_double.__code__) as mon:
    sum_even_double([1, 2, 5, 6, 2])
    mon.show_dump()

Output:
This example shows, from left to right: line number, offset, instruction, instruction argument, and finally the execution order.
If there is a loop, the same instruction may be executed multiple times.

140704398269376=============
   53   0: RESUME                               0                   ... []
   54   2: LOAD_SMALL_INT                       0                   ... ['  1']
   54   4: STORE_FAST                           total               ... ['  2']
   55   6: LOAD_FAST_BORROW                     nums                ... ['  3']
   55   8: GET_ITER                             None                ... ['  4']
   55  10: FOR_ITER                             82                  ... ['  5', ' 15', ' 29', ' 39', ' 53', ' 67']
   55  14: STORE_FAST                           n                   ... ['  6', ' 16', ' 30', ' 40', ' 54']
   56  16: LOAD_FAST_BORROW                     n                   ... ['  7', ' 17', ' 31', ' 41', ' 55']
   56  18: LOAD_SMALL_INT                       2                   ... ['  8', ' 18', ' 32', ' 42', ' 56']
   56  20: BINARY_OP                            6                   ... ['  9', ' 19', ' 33', ' 43', ' 57']
   56  32: LOAD_SMALL_INT                       0                   ... [' 10', ' 20', ' 34', ' 44', ' 58']
   56  34: COMPARE_OP                           ==                  ... [' 11', ' 21', ' 35', ' 45', ' 59']
   56  38: POP_JUMP_IF_TRUE                     48                  ... [' 12', ' 22', ' 36', ' 46', ' 60']
   56  42: NOT_TAKEN                            None                ... [' 13', ' 37']
   56  44: JUMP_BACKWARD                        10                  ... [' 14', ' 38']
   57  48: LOAD_FAST_BORROW_LOAD_FAST_BORROW    ('total', 'n')      ... [' 23', ' 47', ' 61']
   57  50: LOAD_SMALL_INT                       2                   ... [' 24', ' 48', ' 62']
   57  52: BINARY_OP                            5                   ... [' 25', ' 49', ' 63']
   57  64: BINARY_OP                            13                  ... [' 26', ' 50', ' 64']
   57  76: STORE_FAST                           total               ... [' 27', ' 51', ' 65']
   57  78: JUMP_BACKWARD                        10                  ... [' 28', ' 52', ' 66']
   55  82: END_FOR                              None                ... []
   55  84: POP_ITER                             None                ... [' 68']
   58  86: LOAD_FAST_BORROW                     total               ... [' 69']
   58  88: RETURN_VALUE                         None                ... [' 70']

Other Notes

Summary

In this article, we explained usage examples of sys.monitoring. By utilizing this feature, it becomes possible to collect code coverage and create call graphs on your own.

References

Discussion