Returning actual argument expression to a function call?
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Sat Nov 10 02:02:08 EST 2007
En Sat, 10 Nov 2007 03:03:00 -0300, Paddy <paddy3118 at googlemail.com>
escribió:
> 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?
<code test1.py>
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()
</code>
output is like this:
[('test1.py', 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))
Output:
[('test1.py', 18, 'f3', 'return (f1(a and b)')]
[('test1.py', 20, 'f3', 'or f1(c and d))')]
--
Gabriel Genellina
More information about the Python-list
mailing list