How do I dynamically create functions without lambda?
Steven Bethard
steven.bethard at gmail.com
Fri Jan 27 18:28:50 EST 2006
Russell wrote:
> I want my code to be Python 3000 compliant, and hear
> that lambda is being eliminated. The problem is that I
> want to partially bind an existing function with a value
> "foo" that isn't known until run-time:
>
> someobject.newfunc = lambda x: f(foo, x)
>
> The reason a nested function doesn't work for this is
> that it is, well, dynamic. I don't know how many times
> or with what foo's this will be done.
I don't understand this argument here. The code above is almost exactly
equivalent to:
def newfunc(x):
return f(foo, x)
someobject.newfunc = newfunc
Observe:
>>> class C(object):
... pass
...
>>> someobject = C()
>>> someobject.newfunc = lambda x: f(foo, x)
>>> import dis
>>> dis.dis(someobject.newfunc)
1 0 LOAD_GLOBAL 0 (f)
3 LOAD_GLOBAL 1 (foo)
6 LOAD_FAST 0 (x)
9 CALL_FUNCTION 2
12 RETURN_VALUE
>>> def newfunc(x):
... return f(foo, x)
...
>>> someobject.newfunc = newfunc
>>> dis.dis(someobject.newfunc)
2 0 LOAD_GLOBAL 0 (f)
3 LOAD_GLOBAL 1 (foo)
6 LOAD_FAST 0 (x)
9 CALL_FUNCTION 2
12 RETURN_VALUE
Note that both the lambda and the function have exactly the same
byte-code. The only real difference is that if you use a def-statement
instead of a lambda, your function will get a real name, "newfunc",
instead of <lambda>.
STeVe
More information about the Python-list
mailing list