Hi,

Any new scope entered or exited could be traced by defining a custom
tracing function and setting it using the sys
<https://docs.python.org/3/library/sys.html> module through sys.settrace()
<https://docs.python.org/3/library/sys.html#sys.settrace> or
sys.setprofile() <https://docs.python.org/3/library/sys.html#sys.setprofile>.
This is also true for multithreaded applications using the threading
<https://docs.python.org/3/library/threading.html> 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(frame, event, arg):
    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
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/python-ideas@python.org/message/5IH3PHYBKT5MUBJGUYGT2PHNNHRWBDNG/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to