Search code examples
pythonpython-3.xfunctools

Using functools.partial with partial arguments


Trying something out with partial, I observed the following behaviour:

First, I defined a function foo which takes 2 non-keyword arguments:

>>> def foo(salutation, name):
...     print(salutation, name)

Then, I use partial to create a higher order wrapper.

>>> from functools import partial 
>>> f = partial(foo, name='Coldspeed')

Then, called it like this:

>>> f('Hey')

This gave me Hey Coldspeed which was expected. Next, I tried to apply partial to isinstance:

>>> f = partial(isinstance, classinfo=str)
>>> f('hello')

But this gave me an error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: isinstance() takes no keyword arguments 

I tried classinfo as the argument name since that was what was specified in the docs (linked above). It seems that the actual definition does not have the second argument named classinfo as the docs might otherwise state.

How now, would I create a partial function with the second parameter without being forced to specify the argname? I definitely cannot do f = partial(isinstance, str) because str will be taken as the first argument, not the second. If possible, would like to find a way to do this without using lambda functions too.


Solution

  • Unfortunately, that's just not something functools.partial supports. You'd need to write your own version that does support it, or find one in some 3rd-party library somewhere.