Cameron Sparr Cameron Sparr - 1 year ago 89
Python Question

Using Python map() function with keyword arguments

Here is the loop I am trying to use a map function on:

volume_ids = [1,2,3,4,5]
ip = ''
for volume_id in volume_ids:
my_function(volume_id, ip=ip)

is there a way I can do this? It would be trivial if it weren't for the
parameter, but I'm not sure how to deal with that.

Answer Source

Use functools.partial():

from functools import partial

mapfunc = partial(my_function, ip=ip)
map(mapfunc, volume_ids)

partial() creates a new callable, that'll apply any arguments (including keyword arguments) to the wrapped function in addition to whatever is being passed to that new callable.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download