Python: How to get the caller's method name in the called method?

Bit of an amalgamation of the stuff above. But here's my crack at it.

def print_caller_name(stack_size=3): def wrapper(fn): def inner(*args, **kwargs): import inspect stack = inspect.stack() modules = [(index, inspect.getmodule(stack[index][0])) for index in reversed(range(1, stack_size))] module_name_lengths = [len(module.__name__) for _, module in modules] s = '{index:>5} : {module:^%i} : {name}' % (max(module_name_lengths) + 4) callers = ['', s.format(index='level', module='module', name='name'), '-' * 50] for index, module in modules: callers.append(s.format(index=index, module=module.__name__, name=stack[index][3])) callers.append(s.format(index=0, module=fn.__module__, name=fn.__name__)) callers.append('') print('\n'.join(callers)) fn(*args, **kwargs) return inner return wrapper

Use:

@print_caller_name(4)
def foo(): return 'foobar' def bar(): return foo() def baz(): return bar() def fizz(): return baz() fizz()

output is

level : module : name
-------------------------------------------------- 3 : None : fizz 2 : None : baz 1 : None : bar 0 : __main__ : foo

首页 - Wiki
Copyright © 2011-2024 iteam. Current version is 2.125.1. UTC+08:00, 2024-05-18 01:22
浙ICP备14020137号-1 $访客地图$