2

What is the best way to extract arguments when calling function together. How can one function be run so that the other arguments get executed correctly?

How can each iterable be extracted when it is run by the executor?

Greg
  • 8,175
  • 16
  • 72
  • 125

1 Answers1

2

As far as I know, there's no direct way to pass a dictionary and unpacking it using Executor.map.

You need to unpack it manually in single (also need to adjust the function to accept single paramter), or define wrapper function:

import concurrent.futures

def single(a, b):
    return (a, b)

def single_wrapper(d):  # <--- wrapper function to call single(**dict)
    return single(**d)

if __name__ == '__main__':
    iterable = [dict(a=1, b=2), dict(a=3, b=4)]
    with concurrent.futures.ProcessPoolExecutor() as executor:
        results = executor.map(single_wrapper, iterable)  # instead of `single`

    print(list(results))

Alternative: passing two iterables to map:

import concurrent.futures

def single(a, b):
    return (a, b)

if __name__ == '__main__':
    iterable = [dict(a=1,b=2), dict(a=3,b=4)]
    with concurrent.futures.ProcessPoolExecutor() as executor:
        iterable1 = [d['a'] for d in iterable]
        iterable2 = [d['b'] for d in iterable]
        results = executor.map(single, iterable1, iterable2)
        # iterable1[0], iterable2[0] will be passed to single as arguments.
        # iterable1[1], iterable2[1] will be passed to single as arguments.
        # ....

    print(list(results))
falsetru
  • 357,413
  • 63
  • 732
  • 636
  • Can a lambda be used instead of wrapper function? – Greg Mar 07 '17 at 09:26
  • 1
    @Dave, You can't because `lambda` can't be pickled (by default); the object should be serialized before sent to other process. – falsetru Mar 07 '17 at 09:31
  • Is it possible to use other pickle libraries which allow for pickling of lambdas? – Greg Mar 07 '17 at 09:39
  • I meant if it would be possible (without overriding the pickle reference in the concurrent.futures module itself) to change the pickle library the map function uses? – Greg Mar 07 '17 at 11:55
  • Also this may deserve a new question (please let me know if you think it does). How would you deal with constant kwargs? For example if `single` had a bool parameter `c`? How would such a function be executed? – Greg Mar 07 '17 at 13:03
  • @Dave, Sorry, I don't understand your question. You should be better to post a new question with example. – falsetru Mar 07 '17 at 13:26
  • Thanks, here is the link if you would like to have a look: https://stackoverflow.com/questions/42649940 – Greg Mar 07 '17 at 13:46