Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using map() function with keyword arguments

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

volume_ids = [1,2,3,4,5]
ip = '172.12.13.122'
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 ip parameter, but I'm not sure how to deal with that.

like image 550
Cameron Sparr Avatar asked Nov 21 '12 18:11

Cameron Sparr


3 Answers

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.

like image 162
Martijn Pieters Avatar answered Nov 18 '22 18:11

Martijn Pieters


Here is a lambda approach (not better, just different)

volume_ids = [1,2,3,4,5]
ip = '172.12.13.122'
map(lambda ids: my_function(ids, ip), volume_ids);
like image 38
Jason Sperske Avatar answered Nov 18 '22 19:11

Jason Sperske


This can be done easily with a list comprehension.

volume_ids = [1,2,3,4,5]
ip = '172.12.13.122'
results = [my_function(i,ip=ip) for i in volume_ids]
like image 9
shapr Avatar answered Nov 18 '22 18:11

shapr