Returning actual argument expression to a function call?

Piet van Oostrum piet at cs.uu.nl
Sat Nov 10 10:44:23 EST 2007


>>>>> Paddy <paddy3118 at googlemail.com> (P) wrote:

>P> Hi,
>P> # If I have a function definition
>P> def f1(arg):
>P>   global capturecall
>P>   if capturecall:
>P>      ...
>P>   do_normal_stuff(arg)

>P> # and its later use:
>P> def f2():
>P>   ...
>P>   return f1(a  and (b or c))

>P> # I would like to do:
>P> capturecall = False
>P> result = f2()
>P> # And get the equivalent of do_normal_stuff(a and(b or c))

>P> # But also to do:
>P> capturecall = True
>P> result = f2()
>P> # And get the same result, but also save the actual
>P> # calling arguments to f1 either as a string:
>P> #   "a  and (b or c))"
>P> # Or a code object computing a and(b or c)


>P> # I caould change f1 to expect a function instead and do:
>P> def f1b(arg):
>P>   global capturecall
>P>   if capturecall:
>P>      save(arg)
>P>   return do_normal_stuff(arg())

>P> # And then use it like this:
>P> def f2b():
>P>   ...
>P>   return f1b(lambda : (a  and (b or c)) )

>P> # The problem is that for my application to work,
>P> # Python newbies would have to write lambda when they
>P> # know they are after the result. Its my program
>P> # that would require the lambda (or def), which
>P> # is a distraction from their problem.

>P> Any ideas on implementing f1 so I can do f2?

With Python this can't be done without either quoting the expression (make
a string out of it) or using a lambda. Lisp and C# can do this kind of thing.
-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list