do I need to use partial?
Posted
by wiso
on Stack Overflow
See other posts from Stack Overflow
or by wiso
Published on 2010-04-02T10:50:34Z
Indexed on
2010/04/02
10:53 UTC
Read the original article
Hit count: 368
I've a general function, for example (only a simplified example):
def do_operation(operation, a, b, name):
print name
do_something_more(a,b,name, operation(a,b))
def operation_x(a,b):
return a**2 + b
def operation_y(a,b):
return a**10 - b/2.
and some data:
data = {"first": {"name": "first summation", "a": 10, "b": 20, "operation": operation_x},
"second": {"name": "second summation", "a": 20, "b": 50, "operation": operation_y},
"third": {"name": "third summation", "a": 20, "b": 50, "operation": operation_x}, # <-- operation_x again
}
now I can do:
what_to_do = ("first", "third") # this comes from command line
for sum_id in what_to_do:
do_operation(data["operation"], data["a"], data["b"], data["name"])
or maybe it's better if I use functools.partial?
from functools import partial
do_operation_one = do_operation(name=data["first"]["name"], operation=data["first"]["operation"], a=data["first"]["a"], b=data["first"]["b"])
do_operation_two = do_operation(name=data["second"]["name"], operation=data["second"]["operation"] a=data["second"]["a"], b=data["second"]["b"])
do_operation_three = do_operation(name=data["third"]["name"], operation=data["third"]["operation"] a=data["third"]["a"], b=data["third"]["b"])
do_dictionary = { "first": do_operation_one,
"second": do_operation_two,
"third": do_operation_three }
for what in what_to_do:
do_dictionary[what]()
© Stack Overflow or respective owner