Search code examples
pythonpython-3.xfunctional-programmingpython-itertoolsfunctools

How to use kwarg arguments when evaluating a function using map functionality


Below is an example of a test method which is evaluated using a for loop and a kwarg argument.

def test(first_arg='_', second_arg='_'):
    return 'first_arg: %s\t second_arg: %s' % (first_arg, second_arg)

strings = ['a', 'b', 'c', 'd', 'e']

for s in strings:
    print(test(second_arg=s))

How can the same result be achieved using map functionality? That is, how can a kwarg be passed into the map function?:

for i in map(test, strings):
    print(i)

The order of the arguments in the test function cannot be changed and passing all arguments is not acceptable. That is, the below map-equivalent solutions are not desired:

# Passing two arguments is not a desired solution.
for s in strings:
    print(test(first_arg='_', second_arg=s))

OR

# Editing the order of kwargs is also not possible.
def test(second_arg='_', first_arg='_'):
    return 'first_arg: %s\t second_arg: %s' % (first_arg, second_arg)

for s in strings:
    print(test(s))

Solution

  • You can use lambda to create a new function that calls test() with second_arg=x using its only argument x :

    for i in map(lambda x: test(second_arg=x),  strings):
        print(i)
    

    the output:

    first_arg: _     second_arg: a
    first_arg: _     second_arg: b
    first_arg: _     second_arg: c
    first_arg: _     second_arg: d
    first_arg: _     second_arg: e
    

    is the same as for this:

    for s in strings:
        print(test(second_arg=s))
    

    Output:

    first_arg: _     second_arg: a
    first_arg: _     second_arg: b
    first_arg: _     second_arg: c
    first_arg: _     second_arg: d
    first_arg: _     second_arg: e
    

    Alternatively, you can define a helper function. This is equivalent to the solutions with lambda above:

    def call_with_second(x):
        return test(second_arg=x)
    
    for i in map(call_with_second,  strings):
        print(i)
    

    Output:

    first_arg: _     second_arg: a
    first_arg: _     second_arg: b
    first_arg: _     second_arg: c
    first_arg: _     second_arg: d
    first_arg: _     second_arg: e