[Python-Dev] API design question: how to extend sys.settrace()?

Hrvoje Niksic hrvoje.niksic at avl.com
Wed Sep 27 10:44:14 EDT 2017


On 09/27/2017 02:56 PM, Victor Stinner wrote:
> Hi,
> 
> In bpo-29400, it was proposed to add the ability to trace not only
> function calls but also instructions at the bytecode level. I like the
> idea, but I don't see how to extend sys.settrace() to add a new
> "trace_instructions: bool" optional (keyword-only?) parameter without
> breaking the backward compatibility. Should we add a new function
> instead?

One possibility would be for settrace to query the capability on the 
part of the provided callable.

For example:

def settrace(tracefn):
     if getattr(tracefn, '__settrace_trace_instructions__', False):
         ... we need to trace instructions ...

In general, the "trace function" can be upgraded to the concept of a 
"trace object" with (optional) methods under than __call__. This is 
extensible, easy to document, and fully supports the original 
"old=sys.gettrace(); ...; sys.settrace(old)" idiom.


More information about the Python-Dev mailing list