Contents
who call me?
Toggle line numbers
1 #PyOO magic usage @who_called_me
2 def who_called_me(show_filename=False, out=None, indent=' '):
3 def _wrapper(fn):
4 def _inner_wrapper(*args, **kwargs):
5 import sys
6 import inspect
7 output = out or sys.stdout
8 assert hasattr(output, 'write'), \
9 'argument \'out\' of function \'who_called_me\' must have a write method'
10 index = 0
11 stack = inspect.stack()
12 stack.reverse()
13 # remove ourself from the stack list
14 stack.pop()
15 for record in stack:
16 frame = record[0]
17 line = frame.f_lineno
18 func_name = frame.f_code.co_name
19 if show_filename:
20 descr = frame.f_code.co_filename
21 else:
22 descr = frame.f_globals["__name__"]
23 print >>output, '%s%s@%s:%d' % (indent*index, descr, func_name, line)
24 # to be safe explicitly delete the stack frame reference
25 # @see http://docs.python.org/lib/inspect-stack.html
26 del frame
27 index += 1
28 del stack
29 if hasattr(output, 'flush'):
30 output.flush()
31 return fn(*args, **kwargs)
32 return _inner_wrapper
33 return _wrapper
反馈