Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-128644: functools.partial: Allowing trailing Placeholders #128649

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 9 additions & 3 deletions Lib/functools.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,15 @@ def _partial_prepare_merger(args):
else:
order.append(i)
phcount = j - nargs
merger = itemgetter(*order) if phcount else None
if phcount:
if nargs == 1:
i = order[0]
def merger(all_args):
return (all_args[i],)
else:
merger = itemgetter(*order)
else:
merger = None
return phcount, merger

def _partial_new(cls, func, /, *args, **keywords):
Expand All @@ -321,8 +329,6 @@ def _partial_new(cls, func, /, *args, **keywords):
if not callable(func) and not hasattr(func, "__get__"):
raise TypeError(f"the first argument {func!r} must be a callable "
"or a descriptor")
if args and args[-1] is Placeholder:
raise TypeError("trailing Placeholders are not allowed")
if isinstance(func, base_cls):
pto_phcount = func._phcount
tot_args = func.args
Expand Down
30 changes: 20 additions & 10 deletions Lib/test/test_functools.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,11 +211,27 @@ def foo(bar):
p2.new_attr = 'spam'
self.assertEqual(p2.new_attr, 'spam')

def test_placeholders_trailing_raise(self):
def test_trailing_placeholders(self):
PH = self.module.Placeholder
for args in [(PH,), (0, PH), (0, PH, 1, PH, PH, PH)]:
with self.assertRaises(TypeError):
self.partial(capture, *args)
partial = self.partial

# Single Placeholder
p = partial(capture, PH)
actual_args, actual_kwds = p(0)
self.assertEqual(actual_args, (0,))
self.assertEqual(actual_kwds, {})

# 2 arg trailing Placeholder
p = partial(capture, 0, PH)
actual_args, actual_kwds = p(1)
self.assertEqual(actual_args, (0, 1))
self.assertEqual(actual_kwds, {})

# Complex case
p = partial(capture, 0, PH, 2, PH, PH)
actual_args, actual_kwds = p(1, 3, 4)
self.assertEqual(actual_args, (0, 1, 2, 3, 4))
self.assertEqual(actual_kwds, {})

def test_placeholders(self):
PH = self.module.Placeholder
Expand Down Expand Up @@ -368,12 +384,6 @@ def test_setstate(self):
f()
self.assertEqual(f(2), ((2, 1), dict(a=10)))

# Trailing Placeholder error
f = self.partial(signature)
msg_regex = re.escape("trailing Placeholders are not allowed")
with self.assertRaisesRegex(TypeError, f'^{msg_regex}$') as cm:
f.__setstate__((capture, (1, PH), dict(a=10), dict(attr=[])))

def test_setstate_errors(self):
f = self.partial(signature)
self.assertRaises(TypeError, f.__setstate__, (capture, (), {}))
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
:func:`functools.partial` now allows trailing placeholders, which are converted to positional-only arguments.
123 changes: 69 additions & 54 deletions Modules/_functoolsmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -189,13 +189,6 @@ partial_new(PyTypeObject *type, PyObject *args, PyObject *kw)
}
phold = state->placeholder;

/* Placeholder restrictions */
if (new_nargs && PyTuple_GET_ITEM(args, new_nargs) == phold) {
PyErr_SetString(PyExc_TypeError,
"trailing Placeholders are not allowed");
return NULL;
}

/* check wrapped function / object */
pto_args = pto_kw = NULL;
int res = PyObject_TypeCheck(func, state->partial_type);
Expand Down Expand Up @@ -229,55 +222,76 @@ partial_new(PyTypeObject *type, PyObject *args, PyObject *kw)
return NULL;
}

/* Count placeholders */
Py_ssize_t phcount = 0;
for (Py_ssize_t i = 0; i < new_nargs - 1; i++) {
if (PyTuple_GET_ITEM(new_args, i) == phold) {
phcount++;
/* process args */
if (new_nargs == 0) {
if (pto_args == NULL) {
pto->args = PyTuple_New(0);
pto->phcount = 0;
}
else {
pto->args = pto_args;
pto->phcount = pto_phcount;
Py_INCREF(pto_args);
assert(PyTuple_Check(pto->args));
}
}
/* merge args with args of `func` which is `partial` */
if (pto_phcount > 0 && new_nargs > 0) {
Py_ssize_t npargs = PyTuple_GET_SIZE(pto_args);
Py_ssize_t tot_nargs = npargs;
if (new_nargs > pto_phcount) {
tot_nargs += new_nargs - pto_phcount;
else {
/* Count placeholders */
Py_ssize_t phcount = 0;
for (Py_ssize_t i = 0; i < new_nargs; i++) {
if (PyTuple_GET_ITEM(args, i + 1) == phold) {
phcount++;
}
}
PyObject *item;
PyObject *tot_args = PyTuple_New(tot_nargs);
for (Py_ssize_t i = 0, j = 0; i < tot_nargs; i++) {
if (i < npargs) {
item = PyTuple_GET_ITEM(pto_args, i);
if (j < new_nargs && item == phold) {
item = PyTuple_GET_ITEM(new_args, j);
j++;
pto_phcount--;
if (pto_args == NULL) {
new_args = PyTuple_GetSlice(args, 1, new_nargs + 1);
if (new_args == NULL) {
Py_DECREF(pto);
return NULL;
}
pto->args = new_args;
pto->phcount = phcount;
}
else {
/* merge args with args of `func` which is `partial` */
Py_ssize_t npargs = PyTuple_GET_SIZE(pto_args);
Py_ssize_t tot_nargs = npargs;
if (new_nargs > pto_phcount) {
tot_nargs += new_nargs - pto_phcount;
}
PyObject *tot_args = PyTuple_New(tot_nargs);
PyObject *item;
if (pto_phcount > 0) {
for (Py_ssize_t i = 0, j = 0; i < tot_nargs; ++i) {
if (i < npargs) {
item = PyTuple_GET_ITEM(pto_args, i);
if (j < new_nargs && item == phold) {
item = PyTuple_GET_ITEM(args, j + 1);
j++;
pto_phcount--;
}
}
else {
item = PyTuple_GET_ITEM(args, j + 1);
j++;
}
PyTuple_SET_ITEM(tot_args, i, Py_NewRef(item));
}
}
else {
item = PyTuple_GET_ITEM(new_args, j);
j++;
for (Py_ssize_t i = 0; i < npargs; ++i) {
item = PyTuple_GET_ITEM(pto_args, i);
PyTuple_SET_ITEM(tot_args, i, Py_NewRef(item));
}
for (Py_ssize_t i = 0; i < new_nargs; ++i) {
item = PyTuple_GET_ITEM(args, i + 1);
PyTuple_SET_ITEM(tot_args, npargs + i, Py_NewRef(item));
}
}
Py_INCREF(item);
PyTuple_SET_ITEM(tot_args, i, item);
}
pto->args = tot_args;
pto->phcount = pto_phcount + phcount;
Py_DECREF(new_args);
}
else if (pto_args == NULL) {
pto->args = new_args;
pto->phcount = phcount;
}
else {
pto->args = PySequence_Concat(pto_args, new_args);
pto->phcount = pto_phcount + phcount;
Py_DECREF(new_args);
if (pto->args == NULL) {
Py_DECREF(pto);
return NULL;
pto->args = tot_args;
pto->phcount = pto_phcount + phcount;
assert(PyTuple_Check(pto->args));
}
assert(PyTuple_Check(pto->args));
}

if (pto_kw == NULL || PyDict_GET_SIZE(pto_kw) == 0) {
Expand Down Expand Up @@ -402,6 +416,12 @@ partial_vectorcall(PyObject *self, PyObject *const *args,
pto_args, pto_nargs, NULL);
}

/* Fast path if pto_args are all Placeholders */
if (pto_nargs == pto_phcount) {
return _PyObject_VectorcallTstate(tstate, pto->fn,
args, nargs, kwnames);
}

/* Fast path using PY_VECTORCALL_ARGUMENTS_OFFSET to prepend a single
* positional argument */
if (pto_nargs == 1 && (nargsf & PY_VECTORCALL_ARGUMENTS_OFFSET)) {
Expand Down Expand Up @@ -693,13 +713,8 @@ partial_setstate(PyObject *self, PyObject *state)
return NULL;
}

Py_ssize_t nargs = PyTuple_GET_SIZE(fnargs);
if (nargs && PyTuple_GET_ITEM(fnargs, nargs - 1) == pto->placeholder) {
PyErr_SetString(PyExc_TypeError,
"trailing Placeholders are not allowed");
return NULL;
}
/* Count placeholders */
Py_ssize_t nargs = PyTuple_GET_SIZE(fnargs);
Py_ssize_t phcount = 0;
for (Py_ssize_t i = 0; i < nargs - 1; i++) {
if (PyTuple_GET_ITEM(fnargs, i) == pto->placeholder) {
Expand Down
Loading