Skip to content

gh-118402: Fix inspect.signature() for functools.cmp_to_key() result #118427

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

Merged
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/test/test_functools.py
Original file line number Diff line number Diff line change
Expand Up @@ -947,8 +947,13 @@ def mycmp(x, y):
@unittest.skipIf(support.MISSING_C_DOCSTRINGS,
"Signature information for builtins requires docstrings")
def test_cmp_to_signature(self):
self.assertEqual(str(Signature.from_callable(self.cmp_to_key)),
'(mycmp)')
sig = Signature.from_callable(self.cmp_to_key)
self.assertEqual(str(sig), '(mycmp)')
def mycmp(x, y):
return y - x
sig = Signature.from_callable(self.cmp_to_key(mycmp))
self.assertEqual(str(sig), '(obj)')



@unittest.skipUnless(c_functools, 'requires the C _functools module')
Expand Down Expand Up @@ -1864,9 +1869,10 @@ def test_staticmethod(x):
self.assertIsNone(ref())

def test_common_signatures(self):
def orig(): ...
def orig(a, /, b, c=True): ...
lru = self.module.lru_cache(1)(orig)

self.assertEqual(str(Signature.from_callable(lru)), '(a, /, b, c=True)')
self.assertEqual(str(Signature.from_callable(lru.cache_info)), '()')
self.assertEqual(str(Signature.from_callable(lru.cache_clear)), '()')

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix :func:`inspect.signature` for the result of the
:func:`functools.cmp_to_key` call.
12 changes: 12 additions & 0 deletions Modules/_functoolsmodule.c
Original file line number Diff line number Diff line change
Expand Up @@ -571,6 +571,17 @@ static PyMemberDef keyobject_members[] = {
{NULL}
};

static PyObject *
keyobject_text_signature(PyObject *self, void *Py_UNUSED(ignored))
{
return PyUnicode_FromString("(obj)");
}

static PyGetSetDef keyobject_getset[] = {
{"__text_signature__", keyobject_text_signature, (setter)NULL},
{NULL}
};

static PyObject *
keyobject_call(keyobject *ko, PyObject *args, PyObject *kwds);

Expand All @@ -585,6 +596,7 @@ static PyType_Slot keyobject_type_slots[] = {
{Py_tp_clear, keyobject_clear},
{Py_tp_richcompare, keyobject_richcompare},
{Py_tp_members, keyobject_members},
{Py_tp_getset, keyobject_getset},
{0, 0}
};

Expand Down