bpo-42251: Add gettrace and getprofile to threading (GH-23125)
This allows to retrieve the functions that were set in these two, which might differ from sys.gettrace and sys.getprofile within a thread.
diff --git a/Lib/test/test_threading.py b/Lib/test/test_threading.py
index 2f0f3ae..e0e5406 100644
--- a/Lib/test/test_threading.py
+++ b/Lib/test/test_threading.py
@@ -765,6 +765,27 @@ def callback():
finally:
sys.settrace(old_trace)
+ def test_gettrace(self):
+ def noop_trace(frame, event, arg):
+ # no operation
+ return noop_trace
+ old_trace = threading.gettrace()
+ try:
+ threading.settrace(noop_trace)
+ trace_func = threading.gettrace()
+ self.assertEqual(noop_trace,trace_func)
+ finally:
+ threading.settrace(old_trace)
+
+ def test_getprofile(self):
+ def fn(*args): pass
+ old_profile = threading.getprofile()
+ try:
+ threading.setprofile(fn)
+ self.assertEqual(fn, threading.getprofile())
+ finally:
+ threading.setprofile(old_profile)
+
@cpython_only
def test_shutdown_locks(self):
for daemon in (False, True):
diff --git a/Lib/threading.py b/Lib/threading.py
index 06c77f7..d4fe649 100644
--- a/Lib/threading.py
+++ b/Lib/threading.py
@@ -28,7 +28,7 @@
'Event', 'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Thread',
'Barrier', 'BrokenBarrierError', 'Timer', 'ThreadError',
'setprofile', 'settrace', 'local', 'stack_size',
- 'excepthook', 'ExceptHookArgs']
+ 'excepthook', 'ExceptHookArgs', 'gettrace', 'getprofile']
# Rename some stuff so "from threading import *" is safe
_start_new_thread = _thread.start_new_thread
@@ -65,6 +65,10 @@ def setprofile(func):
global _profile_hook
_profile_hook = func
+def getprofile():
+ """Get the profiler function as set by threading.setprofile()."""
+ return _profile_hook
+
def settrace(func):
"""Set a trace function for all threads started from the threading module.
@@ -75,6 +79,10 @@ def settrace(func):
global _trace_hook
_trace_hook = func
+def gettrace():
+ """Get the trace function as set by threading.settrace()."""
+ return _trace_hook
+
# Synchronization classes
Lock = _allocate_lock