Hi,

Any new scope entered or exited could be traced by defining a custom tracing function and setting it using the sys module through sys.settrace() or sys.setprofile(). This is also true for multithreaded applications using the threading module.

Thus, it is rather vague whether the __enter__() and __exit__() functions executed by a with statement could be traced, and if so, in what cases. For instance, _thread.LockType or simply primitive lock objects from threading being used with the context management (i.e. with statement) might not allow us to trace a lock being acquired or released. In other words whether the __enter__() function that calls acquire() is called. After some experimentation, unfortunately this is not the case if either Python or C functions (for CPython) are traced.

So the question whether with-statements could be traced by the python interpreter ought to be clearly stated since in some cases it works and in some doesn't.

_____________________________________________________________________________

EXAMPLE:

import threading
import sys

def tracer(frameeventarg):
    if event == 'call':
        print(f"Entering: {frame.f_code.co_name}")
        return tracer
    elif event == 'c_call':
        print(f"C --- Entering: {arg.__name__}")
    elif event == 'return':
        print(f"Returning: {arg!r}")
    elif event == 'c_return':
        print(f"C --- Returning from: {arg.__name__}")


lock = threading.Lock()

sys.setprofile(tracer)
threading.setprofile(tracer)

print("Begin...")

# In the following case, we would see the C functions 
# being called: acquire and release
lock.acquire()
print("Do some routine with explicit locking")
lock.release()

print("In the middle...")

# In the following case, we cannot see that any locking is happening,
#  nor if the __enter__() and __exit__() methods called
with lock:
    print("Do some routine with locking using context management")

print("End...")

_______________________________________________________________________________________

Best,

Mohamad