Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a kwarg to a wrapped function when wrapper has same arguement

Tags:

python

Lets say a have a function that wraps other functions, like map for instance, whose signature looks like:

def map(func, iterable, *args, **kwargs)

Now lets say I have a function x whose signature is:

def x(a, b=None, c=0, d=100, iterable=list())

If I try to call

map(x, [1,2,3,4], iterable=[5,6,7,8])

I'm going to get a TypeError because the map function has been passed the "iterable" argument twice, even though one of them is intended to the map function and the other to be passed through to the x function.

Is there anyway around this?

like image 858
Ian Sudbery Avatar asked Dec 06 '25 05:12

Ian Sudbery


1 Answers

This is a great place to use functools.partial. This function returns a partial, which will behave like a func allowing map to work, but also will allow you to change keywords ahead of time. In this case all you should have to do is map(functools.partial(x, iterable=[5,6,7,8]), [1,2,3,4])

like image 83
Natecat Avatar answered Dec 07 '25 17:12

Natecat