[Tutor] Function in a data structure
Rodrigues
op73418@mail.telepac.pt
Mon Jun 23 21:24:02 2003
> -----Original Message-----
> From: tutor-admin@python.org
> [mailto:tutor-admin@python.org]On Behalf Of
> Tim Johnson
>
>
> Hello All:
> I'd like to put a function in data structure
> and execute it as part of processing the
> structure.
> I have
> >>fd = {'func':[lambda x: x**2]}
>
Here you a have a dictionary with one pair. The key is the string
'func', but the value is a *list* of one element, precisely the
function object lambda x: x**2. Ditch the [] and your code below will
(almost) work.
> How may I execute the lambda statement which
> is the value for fd['func']?
> I've tried:
> apply(fd['func'],(2))
> and apply(fd['func'],2)
> with no luck
You are not using apply correctly. Firing an interactive prompt:
>>> help(apply)
Help on built-in function apply:
apply(...)
apply(object[, args[, kwargs]]) -> value
Call a callable object with positional arguments taken from the
tuple args,
and keyword arguments taken from the optional dictionary kwargs.
Note that classes are callable, as are instances with a __call__()
method.
>>>
So what you need is:
>>> apply(lambda x:x**2, (2,))
4
Notice the use of (2,) instead of just (2), to build a tuple of one
element only.
By the way, apply is being deprecated, you should be using the *, **
syntax. A simple example should explain how it works:
>>> func = lambda x:x**2
>>> args = (2,)
>>> func(*args)
4
Hope it helps, with my best regards
G. Rodrigues