call a function in Python syntax
Hey im writing a small program in python 2.6 and i have defined 2 helper functions which does almost all i want, for instance
def helper1:
...
def helper2:
...
Now my problem is that i want to mak开发者_开发知识库e a new function that gather the two functions in one function so i dont have to write (in shell):
list(helper1(helper2(argument1,argument2)))
but instead just
function(argument1,argument2)
Is there any short way around that? Im all new to python, or do you need more code-sample to be able to answer?
Thanx in advance for any hints or help
def function(arg1, arg2):
return list(helper1(helper2(arg1, arg2)))
should work.
function = lambda x, y: list(helper1(helper2(x, y)))
This is an example of the higher order function compose
. It's handy to have laying around
def compose(*functions):
""" Returns the composition of functions"""
functions = reversed(functions)
def composition(*args, **kwargs):
func_iter = iter(functions)
ret = next(func_iter)(*args, **kwargs)
for f in func_iter:
ret = f(ret)
return ret
return composition
You can now write your function as
function1 = compose(list, helper1, helper2)
function2 = compose(tuple, helper3, helper4)
function42 = compose(set, helper4, helper2)
etc.
精彩评论