[Tutor] Function in a data structure
Tim Johnson
tim@johnsons-web.com
Mon Jun 23 23:29:01 2003
Hello Rodgrigues:
* Rodrigues <op73418@mail.telepac.pt> [030623 17:32]:
> > -----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
I have found that I can call this function with
>>> fd['func'][0](2)
4
:-) Works for me. But I am still intrigued by your
solution with apply, but do not follow completely.
Please excuse my newbie-lack-of-insite here.
> 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,))
Rodrigues, you are using apply without referencing
the 'lambda' statement from my original dictionary
example. So I am still unclear on how you would use
apply to execute the 'lambda' as a member of the
dictionary. Sorry to be so dense, but maybe I
shouldn't try to cook dinner and code at the same
time.
I find that apply(fd['func'][0],(2,)) also
works, is this what you meant?
Many thanks!
tim
> 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
>
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
--
Tim Johnson <tim@johnsons-web.com>
http://www.alaska-internet-solutions.com
http://www.johnsons-web.com