Returning actual argument expression to a function call?
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Sat Nov 10 01:54:44 EST 2007
On Fri, 09 Nov 2007 22:03:00 -0800, Paddy wrote:
> Hi,
> # If I have a function definition
...
> # The problem is that for my application to work,
> # Python newbies would have to write lambda when they
> # know they are after the result.
I don't understand why you think this is the case.
> Its my program
> # that would require the lambda (or def), which
> # is a distraction from their problem.
...
> Any ideas on implementing f1 so I can do f2?
I've read your post three times now, and I'm still not absolutely sure
what you're trying to accomplish.
I think you want something like this:
You have a function f1(*args) which returns a result. You want a global
flag that tells f1 to stick it's arguments in a global variable. Am I
close?
If so, something like this should work:
# Define someplace to store the arguments.
last_args = (None, None)
# And a flag.
capturecall = True
# A decorator to wrap a function.
def capture_args(func):
def f(*args, **kwargs):
if capturecall:
global last_args
last_args = (args, kwargs)
return func(*args, **kwargs)
f.__name__ = "capturing_" + func.__name__
return f
Now you can do this:
>>> def f1(x, y=3):
... return x + y
...
>>> f1 = capture_args(f1)
>>> f1(5)
8
>>> last_args
((5,), {})
>>> @capture_args
... def f2(x):
... return 2**x
...
>>> f2(0.4+1)
2.6390158215457884
>>> last_args
((1.3999999999999999,), {})
In the second example, if you are trying to capture the expression "0.4
+1", I don't think that is possible. As far as I know, there is no way
for the called function to find out how its arguments were created. I
think if you need that, you need to create your own parser.
--
Steven.
More information about the Python-list
mailing list