Returning actual argument expression to a function call?

Gabriel Genellina gagsl-py2 at
Sat Nov 10 08:02:08 CET 2007

En Sat, 10 Nov 2007 03:03:00 -0300, Paddy <paddy3118 at>  

> Hi,
> # If I have a function definition
> def f1(arg):
>   global capturecall
>   if capturecall:
>      ...
>   do_normal_stuff(arg)
> # and its later use:
> def f2():
>   ...
>   return f1(a  and (b or c))
> # But also to do:
> capturecall = True
> result = f2()
> # And get the same result, but also save the actual
> # calling arguments to f1 either as a string:
> #   "a  and (b or c))"
> # Or a code object computing a and(b or c)

Would be enough to have the source line text?

def extract_caller_info():
     import sys, traceback
     return traceback.extract_stack(sys._getframe(2), limit=1)

def f1(arg):
   if capturecall:
      print extract_caller_info()
   # do_normal_stuff(arg)

def f2():
   a,b,c = 1,0,3
   return f1(a and (b or c))

capturecall = True
result = f2()

output is like this:
[('', 12, 'f2', 'return f1(a and (b or c))')]

source file name, line number, function name, source line text.

> P.S. You might also have multiple calls where I
> would need to capture each individual argument
> expression of f1 e.g:
> def f3():
>   ...
>   return f1(a and b) or e or f1(c and d)

Tell your users that they'll have better results if those two calls are  
split on different lines:

def f3():
    return (f1(a and b)
            or e
            or f1(c and d))

[('', 18, 'f3', 'return (f1(a and b)')]
[('', 20, 'f3', 'or f1(c and d))')]

Gabriel Genellina

More information about the Python-list mailing list