Determine whether a `call` event is a class definition in settrace

Viewed 27

When you use settrace, you can track call events in code execution (among others). However, the documentation mentions:

A function is called (or some other code block entered). The global trace function is called; arg is None; the return value specifies the local trace function.

As far as I can tell, there's no foolproof convenient way to tell when an "other" code block is being entered. This is a problem in my use case where I am trying to determine if a class definition (not an instantiation) has been entered. I see some ways of querying the frame.f_code.co_flags to determine if we are entering a generator, but nothing about classes or anything else that has its own scope.

So far, the only thing I've come up with is based on this detail:

If a code object represents a function, the first item in co_consts is the documentation string of the function, or None if undefined.

So in theory, I could check if the co_consts somehow, but I'm not convinced that that will pay off.

I've also been digging through the CPython source code, and I discovered that the class statement is actually apparently just calling the __build_class__ function, and that is what actually triggers the tracing behavior? I'm not sure if that's correct, or if I missed some other lines of code dedicated to doing it, but then the only reasonable solution seems to be to hook into the __build_class__ infrastructure (which is viable for my use cases).

So here's the code I came up with. But is there a better, more sane way?

0 Answers
Related