calling function pointer from dictionary

5 views
Skip to first unread message

alex goretoy

unread,
Mar 11, 2009, 9:06:48 PM3/11/09
to tulsa...@googlegroups.com
Hello all,

def f(a,b):
    return a+b

If I have a dictionary like this, how to call function with tuple values as args?

d={
    "one": ( f, (1,2)),
    "two": ( f, (2,3))
}

for i in d.keys():
    func,values = d[i]


-Alex Goretoy
http://www.goretoy.com

alex goretoy

unread,
Mar 11, 2009, 9:11:12 PM3/11/09
to tulsa...@googlegroups.com
nevermind, I think I figured it out

>>> for i in d.keys():
...   func,values = d[i]
...   print func(values[0],values[1])
...
5
3

-Alex Goretoy
http://www.goretoy.com

Josh Mize

unread,
Mar 11, 2009, 11:24:02 PM3/11/09
to tulsa...@googlegroups.com
Alex,

If I understood your question correctly, what you're looking for is
called a closure. For the example you gave, the shortest way would be
to use the lambda keyword:

d = {'one': lambda: f(1,2),
'two': lambda: f(3,4)}

However, I generally recommend defining named functions instead of
using lambda, as they are easier to read and debug:

def one():
return f(1,2)

def two():
return f(3,4)

d = {'one': one, 'two': two}


-Josh

alex goretoy

unread,
Mar 12, 2009, 10:18:55 PM3/12/09
to tulsa...@googlegroups.com
I will get to this part after the nested options loop generator and the __import__("jar_name")
-Alex Goretoy
http://www.goretoy.com

alex goretoy

unread,
Mar 21, 2009, 10:21:31 PM3/21/09
to tulsa...@googlegroups.com
Josh, Thanks I see what you mean. I will take your advice.

I will create a pynutbutter-dev group on google groups if anyone wants to join, It will mostly be a discussion about using it and extending it in your own projects (trying to create it, but captcha wont show and i cant finalize it, weird. I will use a diff pc)

-Alex Goretoy
http://www.goretoy.com

Phyllis Diller  - "Never go to bed mad. Stay up and fight."

Reply all
Reply to author
Forward
0 new messages