Passing functions around and executing

Arnaud Delobelle arnodel at googlemail.com
Thu May 15 02:17:19 EDT 2008


alex23 <wuwei23 at gmail.com> writes:

> On May 15, 10:53 am, PatrickMinnesota <PatrickMinnes... at gmail.com>
> wrote:
>> I have a bunch of functions.  I want to put them in a list.  Then I
>> want to pass that list into another function which does some setup and
>> then loops through the list of passed in functions and executes them.
>> Some of them need arguments passed in too.
>
> Hey Patrick,
>
> Is something like the following helpful?
>
>>>> def fn1(): print 'fn1'
>>>> def fn2(): print 'fn2'
>>>> fn_list = [fn1, fn2]
>>>> def process(fn_seq):
> ...     # do set up here
> ...     for fn in fn_list:
> ...         fn()
>
>>>> process(fn_list)
> fn1
> fn2
>
> The easiest way to extend this for optional argument passing would be
> to have each function accept keyword arguments, and then to pass a
> dictionary of arguments in to each:
>
Or you could wrap your functions in functools.partial:

def foo(n):
    return 'x'*n

>>> from functools import partial
>>> foo10 = partial(foo, 10)
>>> print foo10()
xxxxxxxxxx

HTH

-- 
Arnaud



More information about the Python-list mailing list