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

bpo-37645: simplify __str__ of function objects #15295

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
9 changes: 4 additions & 5 deletions Lib/test/test_asyncio/test_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -2155,11 +2155,10 @@ def test_handle_repr(self):
filename, lineno = test_utils.get_function_source(method)
h = asyncio.Handle(cb, (), self.loop)

cb_regex = r'<function HandleTests.test_handle_repr .*>'
cb_regex = (r'functools.partialmethod\(%s, , \)\(\)' % cb_regex)
regex = (r'^<Handle %s at %s:%s>$'
% (cb_regex, re.escape(filename), lineno))
self.assertRegex(repr(h), regex)
cb_repr = "HandleTests.test_handle_repr()"
cb_repr = f"functools.partialmethod({cb_repr}, , )()"
expected = f"<Handle {cb_repr} at {filename}:{lineno}>"
self.assertEqual(repr(h), expected)

def test_handle_repr_debug(self):
self.loop.get_debug.return_value = True
Expand Down
10 changes: 10 additions & 0 deletions Lib/test/test_call.py
Original file line number Diff line number Diff line change
Expand Up @@ -609,5 +609,15 @@ def __call__(self, *args):
self.assertEqual(expected, wrapped(*args, **kwargs))


class TestReprStr(unittest.TestCase):
def test_function(self):
f = testfunction
self.assertEqual(str(f), "testfunction()")
self.assertRegex(repr(f), r"^<function testfunction at .*>$")
f = PythonClass.method
self.assertEqual(str(f), "PythonClass.method()")
self.assertRegex(repr(f), r"^<function PythonClass.method at .*>$")


if __name__ == "__main__":
unittest.main()
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
For a Python function ``f``, ``str(f)`` now returns ``f()`` instead of
``<function f at 0x...>``
9 changes: 8 additions & 1 deletion Objects/funcobject.c
Original file line number Diff line number Diff line change
Expand Up @@ -605,6 +605,13 @@ func_repr(PyFunctionObject *op)
op->func_qualname, op);
}

static PyObject*
func_str(PyFunctionObject *op)
{
return PyUnicode_FromFormat("%U()", op->func_qualname);
}


static int
func_traverse(PyFunctionObject *f, visitproc visit, void *arg)
{
Expand Down Expand Up @@ -649,7 +656,7 @@ PyTypeObject PyFunction_Type = {
0, /* tp_as_mapping */
0, /* tp_hash */
PyVectorcall_Call, /* tp_call */
0, /* tp_str */
(reprfunc)func_str, /* tp_str */
0, /* tp_getattro */
0, /* tp_setattro */
0, /* tp_as_buffer */
Expand Down