repr the call resulting in a stack frame?

223 views Asked by At

Is there a standard method to repr the call that resulted in a given stack frame in Python? Failing that, is there a nice way to do it manually?

As an example:

def some_call(*args, **kwargs):
    print('{}({})'.format(
         'some_call',
         ', '.join(itertools.chain(
             map(repr, args),
             ('{}={!r}'.format(k, kwargs[k]) for k in kwargs)))))

>>> some_call(1, 2, a=3)
some_call(1, 2, a=3)

I'm attempting to log certain calls, and am writing a decorator that logs calls to the wrapped function with full details. Am I going about this wrong?

1

There are 1 answers

0
JimB On BEST ANSWER

I'm not quite sure what you're asking, but you can use the inspect module to get all the current stack info.

f = inspect.currentframe()
print(f.f_locals)
print(inspect.getframeinfo(f))

You can regenerate the calling of your current frame using inspect.getargvalues, and format it to your liking

def some_call(arg1, arg2, *args, **kwargs):
    f = inspect.currentframe()
    fn_name = inspect.getframeinfo(f)[2]
    arginfo = inspect.getargvalues(f)
    args = [repr(arginfo.locals[arg]) for arg in arginfo.args]
    varargs = [repr(x) for x in arginfo.locals[arginfo.varargs]]
    kwargs = [', '.join(str(k)+"="+repr(v) for k,v in 
        arginfo.locals[arginfo.keywords].items())]
    print('{0}({1})'.format(fn_name, ', '.join(args + varargs + kwargs)))

>>> some_call(1, 2, "hi", kw1="frob")
some_call(1, 2, 'hi', kw1='frob')