Passing functions around and executing

P

PatrickMinnesota

I've been reading the docs and looking for an answer and seem stuck.
I'm either not looking in the right places or not understanding what
I'm reading.

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.

Can someone point me to where to read about this? I know it's do-able
since it's basically doing something like a callback would do.

Thanks for any pointers.
 
A

alex23

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()
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:
def fn1(**kwargs): print 'fn1'
def fn2(**kwargs): print 'fn2: x=%(x)s' % kwargs
fn_list = [fn1, fn2]
def process(fn_seq):
.... x = 'hello'
.... for fn in fn_list:
.... fn(**locals())
fn1
fn2: x=hello

You could replace 'process' with a list comprehension:
args = dict(x='hello again')
results = [f(**args) for f in fn_list]
fn1
fn2: x=hello again

Or use 'map':
fn1
fn2: x=hello again

Sorry, I'm a little bored.

- alex23
 
A

Arnaud Delobelle

alex23 said:
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()
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
xxxxxxxxxx

HTH
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top