python function guts

Solutions on MaxInterview for python function guts by the best coders in the world

showing results for - "python function guts"
Salim
15 May 2016
1import sys
2import threading
3
4def show_guts(f):
5    sentinel = object()
6    gutsdata = threading.local()
7    gutsdata.captured_locals = None
8    gutsdata.tracing = False
9
10    def trace_locals(frame, event, arg):
11        if event.startswith('c_'):  # C code traces, no new hook
12            return 
13        if event == 'call':  # start tracing only the first call
14            if gutsdata.tracing:
15                return None
16            gutsdata.tracing = True
17            return trace_locals
18        if event == 'line':  # continue tracing
19            return trace_locals
20
21        # event is either exception or return, capture locals, end tracing
22        gutsdata.captured_locals = frame.f_locals.copy()
23        return None
24
25    def wrapper(*args, **kw):
26        # preserve existing tracer, start our trace
27        old_trace = sys.gettrace()
28        sys.settrace(trace_locals)
29
30        retval = sentinel
31        try:
32            retval = f(*args, **kw)
33        finally:
34            # reinstate existing tracer, report, clean up
35            sys.settrace(old_trace)
36            for key, val in gutsdata.captured_locals.items():
37                print '{}: {!r}'.format(key, val)
38            if retval is not sentinel:
39                print 'Returned: {!r}'.format(retval)
40            gutsdata.captured_locals = None
41            gutsdata.tracing = False
42
43        return retval
44
45    return wrapper
46
similar questions
queries leading to this page
python function guts