newtover newtover - 9 days ago 4x
Python Question

How to fill specific positional arguments with partial in python?

Basically, what I'd like to do is:

>>> from functools import partial
>>> partial(str.startswith, prefix='a')('a')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: startswith() takes no keyword arguments

But more generally the question is, how to fill specific positional arguments with

P.S. I do realize that I can use a


It cannot be done. You have to make a wrapper function.

Ostensibly, you would use keyword arguments, as you tried to do - that's what they're for, right? Unfortunately, as you've discovered, python's standard library functions do not take named parameters. Thus, it is not possible given the current implementation of partial without making another function to run interference.

According to the acceptance of PEP 309, what was accepted for inclusion was "a partial() type constructor binding leftmost positional arguments and any keywords." Furthermore, it states:

Note that when the object is called as though it were a function, positional arguments are appended to those provided to the constructor, and keyword arguments override and augment those provided to the constructor.

Positional arguments, keyword arguments or both can be supplied at when creating the object and when calling it.

Because additional positional arguments are appended, there would be no way to supply some preceding positional argument (by this implementation).

However, it goes on:

Partially applying arguments from the right, or inserting arguments at arbitrary positions creates its own problems, but pending discovery of a good implementation and non-confusing semantics, I don't think it should be ruled out.

So, it apparently could be on the table, but as it stands, it is not implemented that way.

For the sake of disclosure, emphasis in quotes above was my own.