From 9d743338b88ea84e225b46537f678873bfdf6e11 Mon Sep 17 00:00:00 2001 From: Jeroen Demeyer Date: Wed, 14 Aug 2019 22:35:36 +0200 Subject: [PATCH] bpo-37645: simplify __str__ of function objects --- Lib/test/test_asyncio/test_events.py | 9 ++++----- Lib/test/test_call.py | 10 ++++++++++ .../2019-08-14-22-35-30.bpo-37645.Nw3lbT.rst | 2 ++ Objects/funcobject.c | 9 ++++++++- 4 files changed, 24 insertions(+), 6 deletions(-) create mode 100644 Misc/NEWS.d/next/Core and Builtins/2019-08-14-22-35-30.bpo-37645.Nw3lbT.rst diff --git a/Lib/test/test_asyncio/test_events.py b/Lib/test/test_asyncio/test_events.py index 5bc1bc2a621b3d..8e093159f29850 100644 --- a/Lib/test/test_asyncio/test_events.py +++ b/Lib/test/test_asyncio/test_events.py @@ -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'' - cb_regex = (r'functools.partialmethod\(%s, , \)\(\)' % cb_regex) - regex = (r'^$' - % (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"" + self.assertEqual(repr(h), expected) def test_handle_repr_debug(self): self.loop.get_debug.return_value = True diff --git a/Lib/test/test_call.py b/Lib/test/test_call.py index 0bff7ded4670f1..2a9d2c4379a3af 100644 --- a/Lib/test/test_call.py +++ b/Lib/test/test_call.py @@ -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"^$") + f = PythonClass.method + self.assertEqual(str(f), "PythonClass.method()") + self.assertRegex(repr(f), r"^$") + + if __name__ == "__main__": unittest.main() diff --git a/Misc/NEWS.d/next/Core and Builtins/2019-08-14-22-35-30.bpo-37645.Nw3lbT.rst b/Misc/NEWS.d/next/Core and Builtins/2019-08-14-22-35-30.bpo-37645.Nw3lbT.rst new file mode 100644 index 00000000000000..093b2588b6d38e --- /dev/null +++ b/Misc/NEWS.d/next/Core and Builtins/2019-08-14-22-35-30.bpo-37645.Nw3lbT.rst @@ -0,0 +1,2 @@ +For a Python function ``f``, ``str(f)`` now returns ``f()`` instead of +```` diff --git a/Objects/funcobject.c b/Objects/funcobject.c index a65c1f4a55bb4d..15fd0e9a01fc2d 100644 --- a/Objects/funcobject.c +++ b/Objects/funcobject.c @@ -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) { @@ -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 */