Passing functions as parameter (multiprocessing)

Peter Otten __peter__ at
Tue Nov 13 13:51:27 CET 2012

Jean-Michel Pichavant wrote:

> I'm having problems understanding an issue with passing function as
> parameters.

> Here's a code that triggers the issue:
> import multiprocessing
> def f1():
>     print 'I am f1'
> def f2(foo):
>     print 'I am f2 %s' % foo
> workers = [
>         (f1,tuple()),
>         (f2,(5,)),
>         ]
> procs=[]
> for func, parameters in workers:

>     def subproc(*args, **kwargs):
>         return func(*args, **kwargs)
>     procs.append(multiprocessing.Process(target=subproc, args=parameters))

Python has late binding, and when the loop has finished the name func is 
bound to f2. You have created multiple subproc functions, but that doesn't 
matter as they all invoke func aka f2.

A possible fix:

def make_subproc(func):
    def subproc(*args, **kwargs):
        return func(*args, **kwargs)
    return subproc

for func, parameters in workers:

More information about the Python-list mailing list