Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: Dictionary of Functions

Reply
Thread Tools

Re: Dictionary of Functions

 
 
Chris Kaynor
Guest
Posts: n/a
 
      11-15-2012
On Thu, Nov 15, 2012 at 8:04 AM, Kevin Gullikson
<> wrote:
> Hi all,
>
> I am trying to make a dictionary of functions, where each entry in the
> dictionary is the same function with a few of the parameters set to specific
> parameters. My actual use is pretty complicated, but I managed to boil down
> the issue I am having to the following example:
>
> In [1]: def test_fcn(a, x):
> ...: return a*x
> ...:
>
> In [2]: fcn_dict = {}
>
> In [3]: for i in [1,2,3]:
> ...: fcn_dict[i] = lambda x: test_fcn(i, x)
> ...:


In this case, I would recommend using functools.partial instead of a lambda.
It will solve this problem (although MRAB's solution will as well), is
trivially faster (likely insignificant in any real application), and,
IMO, clearer:

for i in [1,2,3]:
fcn_dict[i] = functools.partial(test_fcn, i)

Note that this only works if you are either only specifying the first
arguments by position, or specifying arguments by keyword. There is no
way to specify the second argument by position; you'd have to pass it
as a keyword argument.
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Performance ordered dictionary vs normal dictionary Navkirat Singh Python 6 07-29-2010 10:18 AM
Re: Performance ordered dictionary vs normal dictionary Chris Rebert Python 0 07-29-2010 06:11 AM
creating a dictionary from a dictionary with regex james_027 Python 1 08-22-2007 07:39 AM
[DICTIONARY] - Copy dictionary entries to attributes Ilias Lazaridis Python 6 02-21-2006 11:27 AM
please help me in distinguish redefining functions, overloading functions and overriding functions. Xiangliang Meng C++ 1 06-21-2004 03:11 AM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57