Help with lambda
lallous
elias.bachaalany at gmail.com
Thu Feb 18 08:08:03 EST 2010
On Feb 18, 1:56 pm, "D'Arcy J.M. Cain" <da... at druid.net> wrote:
> On Thu, 18 Feb 2010 04:28:00 -0800 (PST)
>
> lallous <elias.bachaal... at gmail.com> wrote:
> > def make_power(n):
> > return lambda x: x ** n
>
> Hint: type(make_power(2))
>
> Did you expect that to return "int"?
>
No, I expect to see a specialized function.
> > # Create a set of exponential functions
> > f = [lambda x: x ** n for n in xrange(2, 5)]
> > g = [make_power(n) for n in xrange(2, 5)]
>
> The result of make_power(n) is a function that raises it's argument to
> the power of n. I don't know what you are trying to do. Maybe this?
>
> g = [make_power(n)(2) for n in xrange(2, 5)]
> or
> g = [make_power(2)(n) for n in xrange(2, 5)]
>
What I am trying to do is generate different functions.
If you're curious, I was playing with ctypes and wanted to see how it
handles C<->Python callbacks:
CB_T = WINFUNCTYPE(c_int, c_int)
many_cb_t = CFUNCTYPE(c_int, c_int, CB_T)
many_cb = many_cb_t(addressof(c_void_p.in_dll(dll, "many_cb")))
#ANY_SIMPLER
def make_power(n):
return lambda x: x ** n
cbs = [CB_T(make_power(n)) for n in xrange(0, 1000)]
cbs.append(None)
many_cb(3, *cbs)
And the C code in a shared lib:
int many_cb(int value, ...)
{
va_list va;
va = va_start(va, value);
cb_t cb;
int s = 0;
while ( (cb = va_arg(va, cb_t)) != NULL)
{
printf("calling %p", cb);
int r = cb(value);
s += r;
printf(", r=%d\n", r);
}
va_end(va);
return s;
}
Speaking of that, anyone has an idea how to make simpler the line with
#ANY_SIMPLER?
I try: many_cb = CB_T.in_dll(dll, "many_cb") <- but that seems to work
with data items only.
More information about the Python-list
mailing list