为什么输入代码块时没有调用事件?

Why no call event when entering code blocks?

我正在使用 Python 的 sys.settrace 来跟踪程序分析任务的代码执行。

documentation 的说法相反,我没有看到在输入代码块时注册的调用事件。

我正在使用的示例示踪剂如下:

class BasicTracer(object):
    def __init__(self, fun):
        self.fun = fun
        self.result_acc = []
        self.orig_tracer = None

    def trace(self, frame, event, arg):
        self.result_acc.append((event, self.fun(frame)))
        return self.trace

    def setup(self):
        self.orig_tracer = sys.gettrace()
        sys.settrace(self.trace)

    def shutdown(self):
        sys.settrace(self.orig_tracer)

    def run(self, file_path):
        if not os.path.exists(file_path):
            with open('_instrumented.py', 'w') as f:
                f.write(file_path)
                file_path = '_instrumented.py'
        src = open(file_path, 'r').read()
        # compile, execute instrumented version
        namespace = {
            '__name__'      : '__main__',
            '__file__'      : file_path,
            '__builtins__'  : __builtins__,
        }
        compiled = compile(src, filename=file_path, mode='exec')
        self.frame_acc = []
        self.result_acc = []
        self.setup()
        exec(compiled, namespace)
        self.shutdown()

例如,考虑源代码:

src = """
x = 1
while x < 3:
  x += 1
"""

我在退出 while 正文时看到预期的 return 事件,但在进入时没有调用事件。我在这里遗漏了什么吗?

import inspect
tracer = BasicTracer(lambda x: inspect.getframeinfo(x).code_context)
tracer.run(src)
tracer.result_acc
[('call', ['x = 1\n']),
 ('line', ['x = 1\n']),
 ('line', ['while x < 3:\n']),
 ('line', ['  x += 1\n']),
 ('line', ['while x < 3:\n']),
 ('line', ['  x += 1\n']),
 ('line', ['while x < 3:\n']),
 ('return', ['while x < 3:\n']),
 ('call', ['    def shutdown(self):\n']),
 ('line', ['        sys.settrace(self.orig_tracer)\n'])]

我在 Mac OSX 上使用 Python 3.6.3,以防相关。

文档措辞不佳。他们说 'call' 事件发生在

A function is called (or some other code block entered).

但 "some other code block" 指的是任何具有自己的代码 object 和相关范围的东西,而不是像 while.

这样的块