From 9dc577a730ae2ff6e06363c9ac36c144b69b98f4 Mon Sep 17 00:00:00 2001 From: Barry Warsaw Date: Wed, 30 Aug 2017 10:35:49 -0400 Subject: [PATCH 01/27] Watch out for NULL return. Found by Kirit Sankar Gupta. --- Python/compile.c | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Python/compile.c b/Python/compile.c index e547c2fd591c498..c4bb3b8995b9f9d 100644 --- a/Python/compile.c +++ b/Python/compile.c @@ -3360,6 +3360,10 @@ compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end } for (i = begin; i < end; i++) { key = get_const_value((expr_ty)asdl_seq_GET(e->v.Dict.keys, i)); + if (key == NULL) { + Py_DECREF(keys); + return 0; + } Py_INCREF(key); PyTuple_SET_ITEM(keys, i - begin, key); } From bc4634d9e4f514ed4dc88cc1300a4bcf7e0cc3a5 Mon Sep 17 00:00:00 2001 From: Barry Warsaw Date: Mon, 4 Sep 2017 09:53:08 -0700 Subject: [PATCH 02/27] Add a blurb entry for the issue. --- .../Core and Builtins/2017-09-04-09-51-53.bpo-31337.CSt-e_.rst | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 Misc/NEWS.d/next/Core and Builtins/2017-09-04-09-51-53.bpo-31337.CSt-e_.rst diff --git a/Misc/NEWS.d/next/Core and Builtins/2017-09-04-09-51-53.bpo-31337.CSt-e_.rst b/Misc/NEWS.d/next/Core and Builtins/2017-09-04-09-51-53.bpo-31337.CSt-e_.rst new file mode 100644 index 000000000000000..49976f9ffc00d1e --- /dev/null +++ b/Misc/NEWS.d/next/Core and Builtins/2017-09-04-09-51-53.bpo-31337.CSt-e_.rst @@ -0,0 +1,2 @@ +Close a minor NULL deference opportunity in compile.c. Found by Kirit +Sankar Gupta. From f7e3c40b2d23d9fd0abab735bee91786a005b35f Mon Sep 17 00:00:00 2001 From: Barry Warsaw Date: Mon, 4 Sep 2017 09:55:19 -0700 Subject: [PATCH 03/27] Typo in blurb entry. --- .../Core and Builtins/2017-09-04-09-51-53.bpo-31337.CSt-e_.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Misc/NEWS.d/next/Core and Builtins/2017-09-04-09-51-53.bpo-31337.CSt-e_.rst b/Misc/NEWS.d/next/Core and Builtins/2017-09-04-09-51-53.bpo-31337.CSt-e_.rst index 49976f9ffc00d1e..54564b8b3a6e95f 100644 --- a/Misc/NEWS.d/next/Core and Builtins/2017-09-04-09-51-53.bpo-31337.CSt-e_.rst +++ b/Misc/NEWS.d/next/Core and Builtins/2017-09-04-09-51-53.bpo-31337.CSt-e_.rst @@ -1,2 +1,2 @@ -Close a minor NULL deference opportunity in compile.c. Found by Kirit +Close a minor NULL dereference opportunity in compile.c. Found by Kirit Sankar Gupta. From 4600bcf9cd356a7e9364809f5583375592b0ba63 Mon Sep 17 00:00:00 2001 From: Barry Warsaw Date: Mon, 4 Sep 2017 14:58:34 -0700 Subject: [PATCH 04/27] Set an appropriate exception. --- Python/compile.c | 1 + 1 file changed, 1 insertion(+) diff --git a/Python/compile.c b/Python/compile.c index c4bb3b8995b9f9d..c6f5333c64ad275 100644 --- a/Python/compile.c +++ b/Python/compile.c @@ -3362,6 +3362,7 @@ compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end key = get_const_value((expr_ty)asdl_seq_GET(e->v.Dict.keys, i)); if (key == NULL) { Py_DECREF(keys); + PyErr_BadInternalCall(); return 0; } Py_INCREF(key); From 0f46af7dbcec27eac1bedd005b41b6e974566d42 Mon Sep 17 00:00:00 2001 From: Barry Warsaw Date: Mon, 4 Sep 2017 15:47:33 -0700 Subject: [PATCH 05/27] Add a debug() builtin. * debug() calls sys.debughook() * sys.debughook() by default calls pdb.set_trace() * Add sys.__debughook__ to preserve the original. --- Python/bltinmodule.c | 23 +++++++++++++++++++++++ Python/sysmodule.c | 29 +++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) diff --git a/Python/bltinmodule.c b/Python/bltinmodule.c index 5e1f1d3854fc675..181998c7b6cc42b 100644 --- a/Python/bltinmodule.c +++ b/Python/bltinmodule.c @@ -415,6 +415,28 @@ builtin_callable(PyObject *module, PyObject *obj) return PyBool_FromLong((long)PyCallable_Check(obj)); } +static PyObject * +debug(PyObject *self, PyObject *noargs) +{ + PyObject *debughook = PySys_GetObject("debughook"); + PyObject *retval = NULL; + + if (debughook == NULL) { + PyErr_SetString(PyExc_RuntimeError, "lost sys.debughook"); + return NULL; + } + Py_INCREF(debughook); + retval = PyObject_CallObject(debughook, NULL); + Py_DECREF(debughook); + return retval; +} + +PyDoc_STRVAR(debug_doc, +"debug()\n" +"\n" +"Call the sys.debughook() function.\n" +"By default, this drops you into the pdb debugger.\n" +); typedef struct { PyObject_HEAD @@ -2623,6 +2645,7 @@ static PyMethodDef builtin_methods[] = { BUILTIN_CALLABLE_METHODDEF BUILTIN_CHR_METHODDEF BUILTIN_COMPILE_METHODDEF + {"debug", (PyCFunction)debug, METH_NOARGS, debug_doc}, BUILTIN_DELATTR_METHODDEF {"dir", builtin_dir, METH_VARARGS, dir_doc}, BUILTIN_DIVMOD_METHODDEF diff --git a/Python/sysmodule.c b/Python/sysmodule.c index ab435c83104ddc6..419f31d9a20002b 100644 --- a/Python/sysmodule.c +++ b/Python/sysmodule.c @@ -155,6 +155,32 @@ sys_displayhook_unencodable(PyObject *outf, PyObject *o) return ret; } +static PyObject * +sys_debughook(PyObject *self, PyObject *noargs) +{ + PyObject *pdb = PyImport_ImportModule("pdb"); + PyObject *set_trace = NULL; + PyObject *retval = NULL; + + if (pdb == NULL) { + return NULL; + } + set_trace = PyObject_GetAttrString(pdb, "set_trace"); + Py_DECREF(pdb); + if (set_trace == NULL) { + return NULL; + } + retval = PyObject_CallObject(set_trace, NULL); + Py_DECREF(set_trace); + return retval; +} + +PyDoc_STRVAR(debughook_doc, +"debughook()\n" +"\n" +"Called when the built-in debug() function is called.\n" +); + static PyObject * sys_displayhook(PyObject *self, PyObject *o) { @@ -1371,6 +1397,7 @@ static PyMethodDef sys_methods[] = { sys_clear_type_cache__doc__}, {"_current_frames", sys_current_frames, METH_NOARGS, current_frames_doc}, + {"debughook", sys_debughook, METH_NOARGS, debughook_doc}, {"displayhook", sys_displayhook, METH_O, displayhook_doc}, {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc}, {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc}, @@ -1958,6 +1985,8 @@ _PySys_BeginInit(void) PyDict_GetItemString(sysdict, "displayhook")); SET_SYS_FROM_STRING_BORROW("__excepthook__", PyDict_GetItemString(sysdict, "excepthook")); + SET_SYS_FROM_STRING_BORROW("__debughook__", + PyDict_GetItemString(sysdict, "debughook")); SET_SYS_FROM_STRING("version", PyUnicode_FromString(Py_GetVersion())); SET_SYS_FROM_STRING("hexversion", From a141f637377ef5c3d68b397f189417868ee63259 Mon Sep 17 00:00:00 2001 From: Barry Warsaw Date: Mon, 4 Sep 2017 16:15:34 -0700 Subject: [PATCH 06/27] Document the new stuff. --- Doc/library/functions.rst | 46 ++++++++++++++++++++++++--------------- Doc/library/sys.rst | 16 ++++++++++---- 2 files changed, 40 insertions(+), 22 deletions(-) diff --git a/Doc/library/functions.rst b/Doc/library/functions.rst index 015231d9cff225a..05fb0c7c28258b3 100644 --- a/Doc/library/functions.rst +++ b/Doc/library/functions.rst @@ -7,24 +7,24 @@ Built-in Functions The Python interpreter has a number of functions and types built into it that are always available. They are listed here in alphabetical order. -=================== ================= ================== ================ ==================== -.. .. Built-in Functions .. .. -=================== ================= ================== ================ ==================== -:func:`abs` |func-dict|_ :func:`help` :func:`min` :func:`setattr` -:func:`all` :func:`dir` :func:`hex` :func:`next` :func:`slice` -:func:`any` :func:`divmod` :func:`id` :func:`object` :func:`sorted` -:func:`ascii` :func:`enumerate` :func:`input` :func:`oct` :func:`staticmethod` -:func:`bin` :func:`eval` :func:`int` :func:`open` |func-str|_ -:func:`bool` :func:`exec` :func:`isinstance` :func:`ord` :func:`sum` -|func-bytearray|_ :func:`filter` :func:`issubclass` :func:`pow` :func:`super` -|func-bytes|_ :func:`float` :func:`iter` :func:`print` |func-tuple|_ -:func:`callable` :func:`format` :func:`len` :func:`property` :func:`type` -:func:`chr` |func-frozenset|_ |func-list|_ |func-range|_ :func:`vars` -:func:`classmethod` :func:`getattr` :func:`locals` :func:`repr` :func:`zip` -:func:`compile` :func:`globals` :func:`map` :func:`reversed` :func:`__import__` -:func:`complex` :func:`hasattr` :func:`max` :func:`round` -:func:`delattr` :func:`hash` |func-memoryview|_ |func-set|_ -=================== ================= ================== ================ ==================== +=================== ================= ================== ================== ==================== +.. .. Built-in Functions .. .. +=================== ================= ================== ================== ==================== +:func:`abs` :func:`delattr` :func:`hash` |func-memoryview|_ |func-set|_ +:func:`all` |func-dict|_ :func:`help` :func:`min` :func:`setattr` +:func:`any` :func:`dir` :func:`hex` :func:`next` :func:`slice` +:func:`ascii` :func:`divmod` :func:`id` :func:`object` :func:`sorted` +:func:`bin` :func:`enumerate` :func:`input` :func:`oct` :func:`staticmethod` +:func:`bool` :func:`eval` :func:`int` :func:`open` |func-str|_ +|func-bytearray|_ :func:`exec` :func:`isinstance` :func:`ord` :func:`sum` +|func-bytes|_ :func:`filter` :func:`issubclass` :func:`pow` :func:`super` +:func:`callable` :func:`float` :func:`iter` :func:`print` |func-tuple|_ +:func:`chr` :func:`format` :func:`len` :func:`property` :func:`type` +:func:`classmethod` |func-frozenset|_ |func-list|_ |func-range|_ :func:`vars` +:func:`compile` :func:`getattr` :func:`locals` :func:`repr` :func:`zip` +:func:`complex` :func:`globals` :func:`map` :func:`reversed` :func:`__import__` +:func:`debug` :func:`hasattr` :func:`max` :func:`round` +=================== ================= ================== ================== ==================== .. using :func:`dict` would create a link to another page, so local targets are used, with replacement texts to make the output in the table consistent @@ -293,6 +293,16 @@ are always available. They are listed here in alphabetical order. Grouping digits with underscores as in code literals is allowed. +.. function:: debug() + + This function drops you into the debugger at the call site. Specifically, + it calls :func:`sys.debughook` which by default calls + :func:`pdb.set_trace()`. In this case, it is purely a convenience function + so you don't have to explicitly import :mod:`pdb` or type as much code to + enter the debugger. However, :func:`sys.debughook` can be set to some + other function and :func:`debug` will automatically call that, allowing you + to drop into the debugger of choice. + .. function:: delattr(object, name) This is a relative of :func:`setattr`. The arguments are an object and a diff --git a/Doc/library/sys.rst b/Doc/library/sys.rst index 8b94929c500c3a9..2c6400352cd6027 100644 --- a/Doc/library/sys.rst +++ b/Doc/library/sys.rst @@ -109,6 +109,12 @@ always available. This function should be used for internal and specialized purposes only. +.. function:: debughook() + + This hook function is called by built-in :func:`debug`. By default, it + drops you into the :mod:`pdb` debugger, but it can be set to any other + function so that you can choose which debugger gets used. + .. function:: _debugmallocstats() Print low-level information to stderr about the state of CPython's memory @@ -187,12 +193,14 @@ always available. customized by assigning another three-argument function to ``sys.excepthook``. -.. data:: __displayhook__ +.. data:: __debughook__ + __displayhook__ __excepthook__ - These objects contain the original values of ``displayhook`` and ``excepthook`` - at the start of the program. They are saved so that ``displayhook`` and - ``excepthook`` can be restored in case they happen to get replaced with broken + These objects contain the original values of ``debughook``, + ``displayhook``, and ``excepthook`` at the start of the program. They are + saved so that ``debughook``, ``displayhook`` and ``excepthook`` can be + restored in case they happen to get replaced with broken or alternative objects. From 79d7ac8837b5e3273274aacba038af5e0e0a20f0 Mon Sep 17 00:00:00 2001 From: Barry Warsaw Date: Mon, 4 Sep 2017 16:50:19 -0700 Subject: [PATCH 07/27] Add tests for the debug() builtin. Use Argument Clinic for the debug() docstring. --- Lib/test/test_builtin.py | 18 ++++++++++++++++++ Python/bltinmodule.c | 20 +++++++++++--------- Python/clinic/bltinmodule.c.h | 22 +++++++++++++++++++++- 3 files changed, 50 insertions(+), 10 deletions(-) diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py index 9d949b74cb8d0b9..b444f0c4b785396 100644 --- a/Lib/test/test_builtin.py +++ b/Lib/test/test_builtin.py @@ -20,6 +20,7 @@ from operator import neg from test.support import TESTFN, unlink, check_warnings from test.support.script_helper import assert_python_ok +from unittest.mock import patch try: import pty, signal except ImportError: @@ -352,6 +353,23 @@ def f(): """doc""" rv = ns['f']() self.assertEqual(rv, (debugval, docstring)) + def test_debug(self): + with patch('pdb.set_trace') as mock: + debug() + mock.assert_called_once() + + def test_debug_with_debughook_set(self): + call_status = 'Not called' + def my_debughook(): + nonlocal call_status + call_status = 'Called' + try: + sys.debughook = my_debughook + debug() + finally: + sys.debughook = sys.__debughook__ + self.assertEqual(call_status, 'Called') + def test_delattr(self): sys.spam = 1 delattr(sys, 'spam') diff --git a/Python/bltinmodule.c b/Python/bltinmodule.c index 181998c7b6cc42b..3afed0c868cd726 100644 --- a/Python/bltinmodule.c +++ b/Python/bltinmodule.c @@ -415,8 +415,17 @@ builtin_callable(PyObject *module, PyObject *obj) return PyBool_FromLong((long)PyCallable_Check(obj)); } +/*[clinic input] +debug as builtin_debug + +Call the sys.debughook() function. + +By default, this drops you into the pdb debugger. +[clinic start generated code]*/ + static PyObject * -debug(PyObject *self, PyObject *noargs) +builtin_debug_impl(PyObject *module) +/*[clinic end generated code: output=15a7e4ccf2ccd3ca input=ddc119996e60d7ce]*/ { PyObject *debughook = PySys_GetObject("debughook"); PyObject *retval = NULL; @@ -431,13 +440,6 @@ debug(PyObject *self, PyObject *noargs) return retval; } -PyDoc_STRVAR(debug_doc, -"debug()\n" -"\n" -"Call the sys.debughook() function.\n" -"By default, this drops you into the pdb debugger.\n" -); - typedef struct { PyObject_HEAD PyObject *func; @@ -2645,7 +2647,7 @@ static PyMethodDef builtin_methods[] = { BUILTIN_CALLABLE_METHODDEF BUILTIN_CHR_METHODDEF BUILTIN_COMPILE_METHODDEF - {"debug", (PyCFunction)debug, METH_NOARGS, debug_doc}, + BUILTIN_DEBUG_METHODDEF BUILTIN_DELATTR_METHODDEF {"dir", builtin_dir, METH_VARARGS, dir_doc}, BUILTIN_DIVMOD_METHODDEF diff --git a/Python/clinic/bltinmodule.c.h b/Python/clinic/bltinmodule.c.h index fa327da0ffc352b..6f0dc845fec5e64 100644 --- a/Python/clinic/bltinmodule.c.h +++ b/Python/clinic/bltinmodule.c.h @@ -71,6 +71,26 @@ PyDoc_STRVAR(builtin_callable__doc__, #define BUILTIN_CALLABLE_METHODDEF \ {"callable", (PyCFunction)builtin_callable, METH_O, builtin_callable__doc__}, +PyDoc_STRVAR(builtin_debug__doc__, +"debug($module, /)\n" +"--\n" +"\n" +"Call the sys.debughook() function.\n" +"\n" +"By default, this drops you into the pdb debugger."); + +#define BUILTIN_DEBUG_METHODDEF \ + {"debug", (PyCFunction)builtin_debug, METH_NOARGS, builtin_debug__doc__}, + +static PyObject * +builtin_debug_impl(PyObject *module); + +static PyObject * +builtin_debug(PyObject *module, PyObject *Py_UNUSED(ignored)) +{ + return builtin_debug_impl(module); +} + PyDoc_STRVAR(builtin_format__doc__, "format($module, value, format_spec=\'\', /)\n" "--\n" @@ -676,4 +696,4 @@ builtin_issubclass(PyObject *module, PyObject **args, Py_ssize_t nargs) exit: return return_value; } -/*[clinic end generated code: output=09752daa8cdd6ec7 input=a9049054013a1b77]*/ +/*[clinic end generated code: output=e4ac43ce5c7b3e20 input=a9049054013a1b77]*/ From 1666925e4bbe97d856e18c732af53367d18f2d0c Mon Sep 17 00:00:00 2001 From: Barry Warsaw Date: Mon, 4 Sep 2017 16:56:47 -0700 Subject: [PATCH 08/27] Undo a branch leak. --- Python/compile.c | 5 ----- 1 file changed, 5 deletions(-) diff --git a/Python/compile.c b/Python/compile.c index c6f5333c64ad275..e547c2fd591c498 100644 --- a/Python/compile.c +++ b/Python/compile.c @@ -3360,11 +3360,6 @@ compiler_subdict(struct compiler *c, expr_ty e, Py_ssize_t begin, Py_ssize_t end } for (i = begin; i < end; i++) { key = get_const_value((expr_ty)asdl_seq_GET(e->v.Dict.keys, i)); - if (key == NULL) { - Py_DECREF(keys); - PyErr_BadInternalCall(); - return 0; - } Py_INCREF(key); PyTuple_SET_ITEM(keys, i - begin, key); } From 8437033145688294c35a45d175e531b9618350d6 Mon Sep 17 00:00:00 2001 From: Barry Warsaw Date: Mon, 4 Sep 2017 21:14:59 -0700 Subject: [PATCH 09/27] Add versionadded tags and cleanup. --- Doc/library/functions.rst | 2 ++ Doc/library/sys.rst | 5 +++++ .../2017-09-04-09-51-53.bpo-31337.CSt-e_.rst | 2 -- 3 files changed, 7 insertions(+), 2 deletions(-) delete mode 100644 Misc/NEWS.d/next/Core and Builtins/2017-09-04-09-51-53.bpo-31337.CSt-e_.rst diff --git a/Doc/library/functions.rst b/Doc/library/functions.rst index 05fb0c7c28258b3..250e07398dc8997 100644 --- a/Doc/library/functions.rst +++ b/Doc/library/functions.rst @@ -303,6 +303,8 @@ are always available. They are listed here in alphabetical order. other function and :func:`debug` will automatically call that, allowing you to drop into the debugger of choice. + .. versionadded:: 3.7 + .. function:: delattr(object, name) This is a relative of :func:`setattr`. The arguments are an object and a diff --git a/Doc/library/sys.rst b/Doc/library/sys.rst index 2c6400352cd6027..00db31279ed6e21 100644 --- a/Doc/library/sys.rst +++ b/Doc/library/sys.rst @@ -115,6 +115,8 @@ always available. drops you into the :mod:`pdb` debugger, but it can be set to any other function so that you can choose which debugger gets used. + .. versionadded:: 3.7 + .. function:: _debugmallocstats() Print low-level information to stderr about the state of CPython's memory @@ -203,6 +205,9 @@ always available. restored in case they happen to get replaced with broken or alternative objects. + .. versionadded:: 3.7 + __debughook__ + .. function:: exc_info() diff --git a/Misc/NEWS.d/next/Core and Builtins/2017-09-04-09-51-53.bpo-31337.CSt-e_.rst b/Misc/NEWS.d/next/Core and Builtins/2017-09-04-09-51-53.bpo-31337.CSt-e_.rst deleted file mode 100644 index 54564b8b3a6e95f..000000000000000 --- a/Misc/NEWS.d/next/Core and Builtins/2017-09-04-09-51-53.bpo-31337.CSt-e_.rst +++ /dev/null @@ -1,2 +0,0 @@ -Close a minor NULL dereference opportunity in compile.c. Found by Kirit -Sankar Gupta. From ed649facebacf2e26f12d867fb68bafec00e03e9 Mon Sep 17 00:00:00 2001 From: Barry Warsaw Date: Tue, 5 Sep 2017 14:19:18 -0700 Subject: [PATCH 10/27] Add a blurb for PEP 553. --- .../2017-09-05-14-19-02.bpo-31353.oGZUeJ.rst | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 Misc/NEWS.d/next/Core and Builtins/2017-09-05-14-19-02.bpo-31353.oGZUeJ.rst diff --git a/Misc/NEWS.d/next/Core and Builtins/2017-09-05-14-19-02.bpo-31353.oGZUeJ.rst b/Misc/NEWS.d/next/Core and Builtins/2017-09-05-14-19-02.bpo-31353.oGZUeJ.rst new file mode 100644 index 000000000000000..15db7096537e9aa --- /dev/null +++ b/Misc/NEWS.d/next/Core and Builtins/2017-09-05-14-19-02.bpo-31353.oGZUeJ.rst @@ -0,0 +1,5 @@ +PEP 553 - Add a new built-in called ``debug()`` which calls +``sys.debughook()``. By default this imports ``pdb`` and calls +``pdb.set_trace()``, but users may override ``sys.debughook()`` to call +whatever debugger they want. The original value of the hook is saved in +``sys.__debughook__``. From 05b7cae891e4d9a5e917441d01db874bf03d7ed1 Mon Sep 17 00:00:00 2001 From: Barry Warsaw Date: Wed, 6 Sep 2017 14:54:05 -0700 Subject: [PATCH 11/27] debug() -> breakpoint() --- Doc/library/functions.rst | 40 ++++++------- Doc/library/sys.rst | 14 ++--- Lib/test/test_builtin.py | 14 ++--- .../2017-09-05-14-19-02.bpo-31353.oGZUeJ.rst | 8 +-- Python/bltinmodule.c | 22 +++---- Python/clinic/bltinmodule.c.h | 18 +++--- Python/sysmodule.c | 59 ++++++++++--------- 7 files changed, 88 insertions(+), 87 deletions(-) diff --git a/Doc/library/functions.rst b/Doc/library/functions.rst index 250e07398dc8997..8923de12630cde2 100644 --- a/Doc/library/functions.rst +++ b/Doc/library/functions.rst @@ -16,14 +16,14 @@ are always available. They are listed here in alphabetical order. :func:`ascii` :func:`divmod` :func:`id` :func:`object` :func:`sorted` :func:`bin` :func:`enumerate` :func:`input` :func:`oct` :func:`staticmethod` :func:`bool` :func:`eval` :func:`int` :func:`open` |func-str|_ -|func-bytearray|_ :func:`exec` :func:`isinstance` :func:`ord` :func:`sum` -|func-bytes|_ :func:`filter` :func:`issubclass` :func:`pow` :func:`super` -:func:`callable` :func:`float` :func:`iter` :func:`print` |func-tuple|_ -:func:`chr` :func:`format` :func:`len` :func:`property` :func:`type` -:func:`classmethod` |func-frozenset|_ |func-list|_ |func-range|_ :func:`vars` -:func:`compile` :func:`getattr` :func:`locals` :func:`repr` :func:`zip` -:func:`complex` :func:`globals` :func:`map` :func:`reversed` :func:`__import__` -:func:`debug` :func:`hasattr` :func:`max` :func:`round` +:func:`breakpoint` :func:`exec` :func:`isinstance` :func:`ord` :func:`sum` +|func-bytearray|_ :func:`filter` :func:`issubclass` :func:`pow` :func:`super` +|func-bytes|_ :func:`float` :func:`iter` :func:`print` |func-tuple|_ +:func:`callable` :func:`format` :func:`len` :func:`property` :func:`type` +:func:`chr` |func-frozenset|_ |func-list|_ |func-range|_ :func:`vars` +:func:`classmethod` :func:`getattr` :func:`locals` :func:`repr` :func:`zip` +:func:`compile` :func:`globals` :func:`map` :func:`reversed` :func:`__import__` +:func:`complex` :func:`hasattr` :func:`max` :func:`round` =================== ================= ================== ================== ==================== .. using :func:`dict` would create a link to another page, so local targets are @@ -113,6 +113,18 @@ are always available. They are listed here in alphabetical order. .. index:: pair: Boolean; type +.. function:: breakpoint() + + This function drops you into the debugger at the call site. Specifically, + it calls :func:`sys.breakpointhook` which by default calls + :func:`pdb.set_trace()`. In this case, it is purely a convenience function + so you don't have to explicitly import :mod:`pdb` or type as much code to + enter the debugger. However, :func:`sys.breakpointhook` can be set to some + other function and :func:`breakpoint` will automatically call that, + allowing you to drop into the debugger of choice. + + .. versionadded:: 3.7 + .. _func-bytearray: .. class:: bytearray([source[, encoding[, errors]]]) :noindex: @@ -293,18 +305,6 @@ are always available. They are listed here in alphabetical order. Grouping digits with underscores as in code literals is allowed. -.. function:: debug() - - This function drops you into the debugger at the call site. Specifically, - it calls :func:`sys.debughook` which by default calls - :func:`pdb.set_trace()`. In this case, it is purely a convenience function - so you don't have to explicitly import :mod:`pdb` or type as much code to - enter the debugger. However, :func:`sys.debughook` can be set to some - other function and :func:`debug` will automatically call that, allowing you - to drop into the debugger of choice. - - .. versionadded:: 3.7 - .. function:: delattr(object, name) This is a relative of :func:`setattr`. The arguments are an object and a diff --git a/Doc/library/sys.rst b/Doc/library/sys.rst index 00db31279ed6e21..903c544053f2bca 100644 --- a/Doc/library/sys.rst +++ b/Doc/library/sys.rst @@ -109,10 +109,10 @@ always available. This function should be used for internal and specialized purposes only. -.. function:: debughook() +.. function:: breakpointhook() - This hook function is called by built-in :func:`debug`. By default, it - drops you into the :mod:`pdb` debugger, but it can be set to any other + This hook function is called by built-in :func:`breakpoint`. By default, + it drops you into the :mod:`pdb` debugger, but it can be set to any other function so that you can choose which debugger gets used. .. versionadded:: 3.7 @@ -195,18 +195,18 @@ always available. customized by assigning another three-argument function to ``sys.excepthook``. -.. data:: __debughook__ +.. data:: __breakpointhook__ __displayhook__ __excepthook__ - These objects contain the original values of ``debughook``, + These objects contain the original values of ``breakpointhook``, ``displayhook``, and ``excepthook`` at the start of the program. They are - saved so that ``debughook``, ``displayhook`` and ``excepthook`` can be + saved so that ``breakpointhook``, ``displayhook`` and ``excepthook`` can be restored in case they happen to get replaced with broken or alternative objects. .. versionadded:: 3.7 - __debughook__ + __breakpointhook__ .. function:: exc_info() diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py index b444f0c4b785396..4b2bdca0d6b2170 100644 --- a/Lib/test/test_builtin.py +++ b/Lib/test/test_builtin.py @@ -353,21 +353,21 @@ def f(): """doc""" rv = ns['f']() self.assertEqual(rv, (debugval, docstring)) - def test_debug(self): + def test_breakpoint(self): with patch('pdb.set_trace') as mock: - debug() + breakpoint() mock.assert_called_once() - def test_debug_with_debughook_set(self): + def test_breakpoint_with_breakpointhook_set(self): call_status = 'Not called' - def my_debughook(): + def my_breakpointhook(): nonlocal call_status call_status = 'Called' try: - sys.debughook = my_debughook - debug() + sys.breakpointhook = my_breakpointhook + breakpoint() finally: - sys.debughook = sys.__debughook__ + sys.breakpointhook = sys.__breakpointhook__ self.assertEqual(call_status, 'Called') def test_delattr(self): diff --git a/Misc/NEWS.d/next/Core and Builtins/2017-09-05-14-19-02.bpo-31353.oGZUeJ.rst b/Misc/NEWS.d/next/Core and Builtins/2017-09-05-14-19-02.bpo-31353.oGZUeJ.rst index 15db7096537e9aa..800e86cf8817a1b 100644 --- a/Misc/NEWS.d/next/Core and Builtins/2017-09-05-14-19-02.bpo-31353.oGZUeJ.rst +++ b/Misc/NEWS.d/next/Core and Builtins/2017-09-05-14-19-02.bpo-31353.oGZUeJ.rst @@ -1,5 +1,5 @@ -PEP 553 - Add a new built-in called ``debug()`` which calls -``sys.debughook()``. By default this imports ``pdb`` and calls -``pdb.set_trace()``, but users may override ``sys.debughook()`` to call +PEP 553 - Add a new built-in called ``breakpoint()`` which calls +``sys.breakpointhook()``. By default this imports ``pdb`` and calls +``pdb.set_trace()``, but users may override ``sys.breakpointhook()`` to call whatever debugger they want. The original value of the hook is saved in -``sys.__debughook__``. +``sys.__breakpointhook__``. diff --git a/Python/bltinmodule.c b/Python/bltinmodule.c index 76e2b131b72d92a..9669f56b4ec332e 100644 --- a/Python/bltinmodule.c +++ b/Python/bltinmodule.c @@ -416,27 +416,27 @@ builtin_callable(PyObject *module, PyObject *obj) } /*[clinic input] -debug as builtin_debug +breakpoint as builtin_breakpoint -Call the sys.debughook() function. +Call the sys.breakpointhook() function. By default, this drops you into the pdb debugger. [clinic start generated code]*/ static PyObject * -builtin_debug_impl(PyObject *module) -/*[clinic end generated code: output=15a7e4ccf2ccd3ca input=ddc119996e60d7ce]*/ +builtin_breakpoint_impl(PyObject *module) +/*[clinic end generated code: output=31a2b40a5bce5816 input=ad4bff59a1be4b8e]*/ { - PyObject *debughook = PySys_GetObject("debughook"); + PyObject *hook = PySys_GetObject("breakpointhook"); PyObject *retval = NULL; - if (debughook == NULL) { - PyErr_SetString(PyExc_RuntimeError, "lost sys.debughook"); + if (hook == NULL) { + PyErr_SetString(PyExc_RuntimeError, "lost sys.breakpointhook"); return NULL; } - Py_INCREF(debughook); - retval = PyObject_CallObject(debughook, NULL); - Py_DECREF(debughook); + Py_INCREF(hook); + retval = PyObject_CallObject(hook, NULL); + Py_DECREF(hook); return retval; } @@ -2644,10 +2644,10 @@ static PyMethodDef builtin_methods[] = { BUILTIN_ANY_METHODDEF BUILTIN_ASCII_METHODDEF BUILTIN_BIN_METHODDEF + BUILTIN_BREAKPOINT_METHODDEF BUILTIN_CALLABLE_METHODDEF BUILTIN_CHR_METHODDEF BUILTIN_COMPILE_METHODDEF - BUILTIN_DEBUG_METHODDEF BUILTIN_DELATTR_METHODDEF {"dir", builtin_dir, METH_VARARGS, dir_doc}, BUILTIN_DIVMOD_METHODDEF diff --git a/Python/clinic/bltinmodule.c.h b/Python/clinic/bltinmodule.c.h index 6f0dc845fec5e64..9a46e27b8c5b565 100644 --- a/Python/clinic/bltinmodule.c.h +++ b/Python/clinic/bltinmodule.c.h @@ -71,24 +71,24 @@ PyDoc_STRVAR(builtin_callable__doc__, #define BUILTIN_CALLABLE_METHODDEF \ {"callable", (PyCFunction)builtin_callable, METH_O, builtin_callable__doc__}, -PyDoc_STRVAR(builtin_debug__doc__, -"debug($module, /)\n" +PyDoc_STRVAR(builtin_breakpoint__doc__, +"breakpoint($module, /)\n" "--\n" "\n" -"Call the sys.debughook() function.\n" +"Call the sys.breakpointhook() function.\n" "\n" "By default, this drops you into the pdb debugger."); -#define BUILTIN_DEBUG_METHODDEF \ - {"debug", (PyCFunction)builtin_debug, METH_NOARGS, builtin_debug__doc__}, +#define BUILTIN_BREAKPOINT_METHODDEF \ + {"breakpoint", (PyCFunction)builtin_breakpoint, METH_NOARGS, builtin_breakpoint__doc__}, static PyObject * -builtin_debug_impl(PyObject *module); +builtin_breakpoint_impl(PyObject *module); static PyObject * -builtin_debug(PyObject *module, PyObject *Py_UNUSED(ignored)) +builtin_breakpoint(PyObject *module, PyObject *Py_UNUSED(ignored)) { - return builtin_debug_impl(module); + return builtin_breakpoint_impl(module); } PyDoc_STRVAR(builtin_format__doc__, @@ -696,4 +696,4 @@ builtin_issubclass(PyObject *module, PyObject **args, Py_ssize_t nargs) exit: return return_value; } -/*[clinic end generated code: output=e4ac43ce5c7b3e20 input=a9049054013a1b77]*/ +/*[clinic end generated code: output=d63bb279b3be5cbe input=a9049054013a1b77]*/ diff --git a/Python/sysmodule.c b/Python/sysmodule.c index 70c78df685b4970..444191772260e80 100644 --- a/Python/sysmodule.c +++ b/Python/sysmodule.c @@ -93,6 +93,32 @@ PySys_SetObject(const char *name, PyObject *v) return PyDict_SetItemString(sd, name, v); } +static PyObject * +sys_breakpointhook(PyObject *self, PyObject *noargs) +{ + PyObject *pdb = PyImport_ImportModule("pdb"); + PyObject *set_trace = NULL; + PyObject *retval = NULL; + + if (pdb == NULL) { + return NULL; + } + set_trace = PyObject_GetAttrString(pdb, "set_trace"); + Py_DECREF(pdb); + if (set_trace == NULL) { + return NULL; + } + retval = PyObject_CallObject(set_trace, NULL); + Py_DECREF(set_trace); + return retval; +} + +PyDoc_STRVAR(breakpointhook_doc, +"breakpointhook()\n" +"\n" +"Called when the built-in breakpoint() function is called.\n" +); + /* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace' error handler. If sys.stdout has a buffer attribute, use sys.stdout.buffer.write(encoded), otherwise redecode the string and use @@ -155,32 +181,6 @@ sys_displayhook_unencodable(PyObject *outf, PyObject *o) return ret; } -static PyObject * -sys_debughook(PyObject *self, PyObject *noargs) -{ - PyObject *pdb = PyImport_ImportModule("pdb"); - PyObject *set_trace = NULL; - PyObject *retval = NULL; - - if (pdb == NULL) { - return NULL; - } - set_trace = PyObject_GetAttrString(pdb, "set_trace"); - Py_DECREF(pdb); - if (set_trace == NULL) { - return NULL; - } - retval = PyObject_CallObject(set_trace, NULL); - Py_DECREF(set_trace); - return retval; -} - -PyDoc_STRVAR(debughook_doc, -"debughook()\n" -"\n" -"Called when the built-in debug() function is called.\n" -); - static PyObject * sys_displayhook(PyObject *self, PyObject *o) { @@ -1389,13 +1389,13 @@ sys_getandroidapilevel(PyObject *self) static PyMethodDef sys_methods[] = { /* Might as well keep this in alphabetic order */ + {"breakpointhook", sys_breakpointhook, METH_NOARGS, breakpointhook_doc}, {"callstats", (PyCFunction)sys_callstats, METH_NOARGS, callstats_doc}, {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS, sys_clear_type_cache__doc__}, {"_current_frames", sys_current_frames, METH_NOARGS, current_frames_doc}, - {"debughook", sys_debughook, METH_NOARGS, debughook_doc}, {"displayhook", sys_displayhook, METH_O, displayhook_doc}, {"exc_info", sys_exc_info, METH_NOARGS, exc_info_doc}, {"excepthook", sys_excepthook, METH_VARARGS, excepthook_doc}, @@ -1983,8 +1983,9 @@ _PySys_BeginInit(void) PyDict_GetItemString(sysdict, "displayhook")); SET_SYS_FROM_STRING_BORROW("__excepthook__", PyDict_GetItemString(sysdict, "excepthook")); - SET_SYS_FROM_STRING_BORROW("__debughook__", - PyDict_GetItemString(sysdict, "debughook")); + SET_SYS_FROM_STRING_BORROW( + "__breakpointhook__", + PyDict_GetItemString(sysdict, "breakpointhook")); SET_SYS_FROM_STRING("version", PyUnicode_FromString(Py_GetVersion())); SET_SYS_FROM_STRING("hexversion", From 6b9a59c971c16876c0a9042d59c2023a3bcc40d5 Mon Sep 17 00:00:00 2001 From: Barry Warsaw Date: Wed, 6 Sep 2017 15:29:11 -0700 Subject: [PATCH 12/27] Add a test for breakpointhook reset. --- Lib/test/test_builtin.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py index 4b2bdca0d6b2170..58f8218805cf825 100644 --- a/Lib/test/test_builtin.py +++ b/Lib/test/test_builtin.py @@ -370,6 +370,21 @@ def my_breakpointhook(): sys.breakpointhook = sys.__breakpointhook__ self.assertEqual(call_status, 'Called') + def test_breakpoint_with_breakpointhook_reset(self): + call_status = 'Not called' + def my_breakpointhook(): + nonlocal call_status + call_status = 'Called' + try: + sys.breakpointhook = my_breakpointhook + breakpoint() + finally: + sys.breakpointhook = sys.__breakpointhook__ + self.assertEqual(call_status, 'Called') + with patch('pdb.set_trace') as mock: + breakpoint() + mock.assert_called_once() + def test_delattr(self): sys.spam = 1 delattr(sys, 'spam') From c57d0dc69857af597b55ef9035363368620f8f19 Mon Sep 17 00:00:00 2001 From: Barry Warsaw Date: Thu, 7 Sep 2017 11:10:18 -0700 Subject: [PATCH 13/27] Signature changed to breakpoint(*args, **kws). --- Lib/test/test_builtin.py | 21 +++++++++++++++++++++ Lib/test/test_inspect.py | 3 ++- Python/bltinmodule.c | 24 ++++++++++++------------ Python/clinic/bltinmodule.c.h | 22 +--------------------- 4 files changed, 36 insertions(+), 34 deletions(-) diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py index 58f8218805cf825..25da66846ad56c0 100644 --- a/Lib/test/test_builtin.py +++ b/Lib/test/test_builtin.py @@ -385,6 +385,27 @@ def my_breakpointhook(): breakpoint() mock.assert_called_once() + def test_breakpoint_with_args_and_keywords(self): + call_args = None + def my_breakpointhook(*args, **kws): + nonlocal call_args + call_args = args, kws + try: + sys.breakpointhook = my_breakpointhook + breakpoint(1, 2, 3, four=4, five=5) + finally: + sys.breakpointhook = sys.__breakpointhook__ + self.assertEqual(call_args, ((1, 2, 3), dict(four=4, five=5))) + + def test_breakpoint_with_passthru_error(self): + def my_breakpointhook(): + pass + try: + sys.breakpointhook = my_breakpointhook + self.assertRaises(TypeError, breakpoint, 1, 2, 3, four=4, five=5) + finally: + sys.breakpointhook = sys.__breakpointhook__ + def test_delattr(self): sys.spam = 1 delattr(sys, 'spam') diff --git a/Lib/test/test_inspect.py b/Lib/test/test_inspect.py index 350d5dbd776ac2f..22db3d0e8926d69 100644 --- a/Lib/test/test_inspect.py +++ b/Lib/test/test_inspect.py @@ -3523,7 +3523,8 @@ def test_builtins_have_signatures(self): needs_semantic_update = {"round"} no_signature |= needs_semantic_update # These need *args support in Argument Clinic - needs_varargs = {"min", "max", "print", "__build_class__"} + needs_varargs = {"breakpoint", "min", "max", "print", + "__build_class__"} no_signature |= needs_varargs # These simply weren't covered in the initial AC conversion # for builtin callables diff --git a/Python/bltinmodule.c b/Python/bltinmodule.c index 9669f56b4ec332e..aa40b479f77f91c 100644 --- a/Python/bltinmodule.c +++ b/Python/bltinmodule.c @@ -415,17 +415,8 @@ builtin_callable(PyObject *module, PyObject *obj) return PyBool_FromLong((long)PyCallable_Check(obj)); } -/*[clinic input] -breakpoint as builtin_breakpoint - -Call the sys.breakpointhook() function. - -By default, this drops you into the pdb debugger. -[clinic start generated code]*/ - static PyObject * -builtin_breakpoint_impl(PyObject *module) -/*[clinic end generated code: output=31a2b40a5bce5816 input=ad4bff59a1be4b8e]*/ +builtin_breakpoint(PyObject *self, PyObject *args, PyObject *keywords) { PyObject *hook = PySys_GetObject("breakpointhook"); PyObject *retval = NULL; @@ -435,11 +426,20 @@ builtin_breakpoint_impl(PyObject *module) return NULL; } Py_INCREF(hook); - retval = PyObject_CallObject(hook, NULL); + retval = PyObject_Call(hook, args, keywords); Py_DECREF(hook); return retval; } +PyDoc_STRVAR(breakpoint_doc, +"breakpoint(*args, **kws)\n\ +\n\ +Call the sys.breakpointhook() function, passing *args and **kws\n\ +through unchanged. sys.breakpointhook() must accept the arguments\n\ +passed.\n\ +\n\ +By default, this drops you into the pdb debugger."); + typedef struct { PyObject_HEAD PyObject *func; @@ -2644,7 +2644,7 @@ static PyMethodDef builtin_methods[] = { BUILTIN_ANY_METHODDEF BUILTIN_ASCII_METHODDEF BUILTIN_BIN_METHODDEF - BUILTIN_BREAKPOINT_METHODDEF + {"breakpoint", (PyCFunction)builtin_breakpoint, METH_VARARGS | METH_KEYWORDS, breakpoint_doc}, BUILTIN_CALLABLE_METHODDEF BUILTIN_CHR_METHODDEF BUILTIN_COMPILE_METHODDEF diff --git a/Python/clinic/bltinmodule.c.h b/Python/clinic/bltinmodule.c.h index 9a46e27b8c5b565..fa327da0ffc352b 100644 --- a/Python/clinic/bltinmodule.c.h +++ b/Python/clinic/bltinmodule.c.h @@ -71,26 +71,6 @@ PyDoc_STRVAR(builtin_callable__doc__, #define BUILTIN_CALLABLE_METHODDEF \ {"callable", (PyCFunction)builtin_callable, METH_O, builtin_callable__doc__}, -PyDoc_STRVAR(builtin_breakpoint__doc__, -"breakpoint($module, /)\n" -"--\n" -"\n" -"Call the sys.breakpointhook() function.\n" -"\n" -"By default, this drops you into the pdb debugger."); - -#define BUILTIN_BREAKPOINT_METHODDEF \ - {"breakpoint", (PyCFunction)builtin_breakpoint, METH_NOARGS, builtin_breakpoint__doc__}, - -static PyObject * -builtin_breakpoint_impl(PyObject *module); - -static PyObject * -builtin_breakpoint(PyObject *module, PyObject *Py_UNUSED(ignored)) -{ - return builtin_breakpoint_impl(module); -} - PyDoc_STRVAR(builtin_format__doc__, "format($module, value, format_spec=\'\', /)\n" "--\n" @@ -696,4 +676,4 @@ builtin_issubclass(PyObject *module, PyObject **args, Py_ssize_t nargs) exit: return return_value; } -/*[clinic end generated code: output=d63bb279b3be5cbe input=a9049054013a1b77]*/ +/*[clinic end generated code: output=09752daa8cdd6ec7 input=a9049054013a1b77]*/ From 244bff56f9ee2b9e112d020f9b8c5d19b52b8fb3 Mon Sep 17 00:00:00 2001 From: Barry Warsaw Date: Thu, 7 Sep 2017 11:24:11 -0700 Subject: [PATCH 14/27] Update documentation. --- Doc/library/functions.rst | 16 +++++++++------- Doc/library/sys.rst | 7 +++++++ 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/Doc/library/functions.rst b/Doc/library/functions.rst index 8923de12630cde2..08093e61fe527d7 100644 --- a/Doc/library/functions.rst +++ b/Doc/library/functions.rst @@ -113,15 +113,17 @@ are always available. They are listed here in alphabetical order. .. index:: pair: Boolean; type -.. function:: breakpoint() +.. function:: breakpoint(*args, **kws) This function drops you into the debugger at the call site. Specifically, - it calls :func:`sys.breakpointhook` which by default calls - :func:`pdb.set_trace()`. In this case, it is purely a convenience function - so you don't have to explicitly import :mod:`pdb` or type as much code to - enter the debugger. However, :func:`sys.breakpointhook` can be set to some - other function and :func:`breakpoint` will automatically call that, - allowing you to drop into the debugger of choice. + it calls :func:`sys.breakpointhook`, passing ``args`` and ``kws`` straight + through. By default, ``sys.breakpointhook()`` calls + :func:`pdb.set_trace()` expecting no arguments. In this case, it is + purely a convenience function so you don't have to explicitly import + :mod:`pdb` or type as much code to enter the debugger. However, + :func:`sys.breakpointhook` can be set to some other function and + :func:`breakpoint` will automatically call that, allowing you to drop into + the debugger of choice. .. versionadded:: 3.7 diff --git a/Doc/library/sys.rst b/Doc/library/sys.rst index 903c544053f2bca..1c414d8f7c40fee 100644 --- a/Doc/library/sys.rst +++ b/Doc/library/sys.rst @@ -115,6 +115,13 @@ always available. it drops you into the :mod:`pdb` debugger, but it can be set to any other function so that you can choose which debugger gets used. + The signature of this function is dependent on what it calls. For example, + the default binding (e.g. ``pdb.set_trace()``) expects no arguments, but + you might bind it to a function that expects additional arguments + (positional and/or keyword). The built-in ``breakpoint()`` function passes + its ``*args`` and ``**kws`` straight through. Whatever + ``breakpointhooks()`` returns is returned from ``breakpoint()``. + .. versionadded:: 3.7 .. function:: _debugmallocstats() From 6eb3470c50b5c28e3b9b55d7756b885f123c9415 Mon Sep 17 00:00:00 2001 From: Barry Warsaw Date: Thu, 7 Sep 2017 14:20:14 -0700 Subject: [PATCH 15/27] Make patchheck happy. --- Lib/test/test_inspect.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Lib/test/test_inspect.py b/Lib/test/test_inspect.py index 22db3d0e8926d69..819fcc585376aad 100644 --- a/Lib/test/test_inspect.py +++ b/Lib/test/test_inspect.py @@ -2018,7 +2018,7 @@ def test_staticmethod(*args): # NOQA ((('args', ..., ..., 'var_positional'),), ...)) self.assertEqual(self.signature(A.f3), ((('args', ..., ..., 'var_positional'),), ...)) - self.assertEqual(self.signature(A.f4), + self.assertEqual(self.signature(A.f4), ((('args', ..., ..., 'var_positional'), ('kwargs', ..., ..., 'var_keyword')), ...)) @cpython_only From f3200c7003a72550823e97e9a06befedcf62fb9e Mon Sep 17 00:00:00 2001 From: Barry Warsaw Date: Fri, 8 Sep 2017 15:15:12 -0700 Subject: [PATCH 16/27] Support $PYTHONBREAKPOINT --- Lib/test/test_builtin.py | 164 ++++++++++++++++++++++++++------------- Python/bltinmodule.c | 74 ++++++++++++++++-- 2 files changed, 178 insertions(+), 60 deletions(-) diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py index 25da66846ad56c0..aea42c3b3126691 100644 --- a/Lib/test/test_builtin.py +++ b/Lib/test/test_builtin.py @@ -17,8 +17,9 @@ import types import unittest import warnings +from contextlib import ExitStack from operator import neg -from test.support import TESTFN, unlink, check_warnings +from test.support import EnvironmentVarGuard, TESTFN, unlink, check_warnings from test.support.script_helper import assert_python_ok from unittest.mock import patch try: @@ -353,59 +354,6 @@ def f(): """doc""" rv = ns['f']() self.assertEqual(rv, (debugval, docstring)) - def test_breakpoint(self): - with patch('pdb.set_trace') as mock: - breakpoint() - mock.assert_called_once() - - def test_breakpoint_with_breakpointhook_set(self): - call_status = 'Not called' - def my_breakpointhook(): - nonlocal call_status - call_status = 'Called' - try: - sys.breakpointhook = my_breakpointhook - breakpoint() - finally: - sys.breakpointhook = sys.__breakpointhook__ - self.assertEqual(call_status, 'Called') - - def test_breakpoint_with_breakpointhook_reset(self): - call_status = 'Not called' - def my_breakpointhook(): - nonlocal call_status - call_status = 'Called' - try: - sys.breakpointhook = my_breakpointhook - breakpoint() - finally: - sys.breakpointhook = sys.__breakpointhook__ - self.assertEqual(call_status, 'Called') - with patch('pdb.set_trace') as mock: - breakpoint() - mock.assert_called_once() - - def test_breakpoint_with_args_and_keywords(self): - call_args = None - def my_breakpointhook(*args, **kws): - nonlocal call_args - call_args = args, kws - try: - sys.breakpointhook = my_breakpointhook - breakpoint(1, 2, 3, four=4, five=5) - finally: - sys.breakpointhook = sys.__breakpointhook__ - self.assertEqual(call_args, ((1, 2, 3), dict(four=4, five=5))) - - def test_breakpoint_with_passthru_error(self): - def my_breakpointhook(): - pass - try: - sys.breakpointhook = my_breakpointhook - self.assertRaises(TypeError, breakpoint, 1, 2, 3, four=4, five=5) - finally: - sys.breakpointhook = sys.__breakpointhook__ - def test_delattr(self): sys.spam = 1 delattr(sys, 'spam') @@ -1565,6 +1513,114 @@ def test_construct_singletons(self): self.assertRaises(TypeError, tp, 1, 2) self.assertRaises(TypeError, tp, a=1, b=2) + +class TestBreakpoint(unittest.TestCase): + def test_breakpoint(self): + with patch('pdb.set_trace') as mock: + breakpoint() + mock.assert_called_once() + + def test_breakpoint_with_breakpointhook_set(self): + call_status = 'Not called' + def my_breakpointhook(): + nonlocal call_status + call_status = 'Called' + try: + sys.breakpointhook = my_breakpointhook + breakpoint() + finally: + sys.breakpointhook = sys.__breakpointhook__ + self.assertEqual(call_status, 'Called') + + def test_breakpoint_with_breakpointhook_reset(self): + call_status = 'Not called' + def my_breakpointhook(): + nonlocal call_status + call_status = 'Called' + try: + sys.breakpointhook = my_breakpointhook + breakpoint() + finally: + sys.breakpointhook = sys.__breakpointhook__ + self.assertEqual(call_status, 'Called') + with patch('pdb.set_trace') as mock: + breakpoint() + mock.assert_called_once() + + def test_breakpoint_with_args_and_keywords(self): + call_args = None + def my_breakpointhook(*args, **kws): + nonlocal call_args + call_args = args, kws + try: + sys.breakpointhook = my_breakpointhook + breakpoint(1, 2, 3, four=4, five=5) + finally: + sys.breakpointhook = sys.__breakpointhook__ + self.assertEqual(call_args, ((1, 2, 3), dict(four=4, five=5))) + + def test_breakpoint_with_passthru_error(self): + def my_breakpointhook(): + pass + try: + sys.breakpointhook = my_breakpointhook + self.assertRaises(TypeError, breakpoint, 1, 2, 3, four=4, five=5) + finally: + sys.breakpointhook = sys.__breakpointhook__ + + def test_envar_good_path_builtin(self): + with ExitStack() as resources: + env = resources.enter_context(EnvironmentVarGuard()) + env['PYTHONBREAKPOINT'] = 'int' + mock = resources.enter_context(patch('builtins.int')) + breakpoint('7') + mock.assert_called_once_with('7') + + def test_envar_good_path_other(self): + with ExitStack() as resources: + env = resources.enter_context(EnvironmentVarGuard()) + env['PYTHONBREAKPOINT'] = 'sys.exit' + mock = resources.enter_context(patch('sys.exit')) + breakpoint() + mock.assert_called_once_with() + + def test_envar_good_path_noop_0(self): + with ExitStack() as resources: + env = resources.enter_context(EnvironmentVarGuard()) + env['PYTHONBREAKPOINT'] = '0' + mock = resources.enter_context(patch('pdb.set_trace')) + breakpoint() + mock.assert_not_called() + + def test_envar_good_path_empty_string(self): + # PYTHONBREAKPOINT='' is the same as it not being set. + with ExitStack() as resources: + env = resources.enter_context(EnvironmentVarGuard()) + env['PYTHONBREAKPOINT'] = '' + mock = resources.enter_context(patch('pdb.set_trace')) + breakpoint() + mock.assert_called_once_with() + + def test_envar_unimportable(self): + for envar in ( + '.', '..', '.foo', 'foo.', '.int', 'int.' + 'nosuchbuiltin', + 'nosuchmodule.nosuchcallable', + ): + with self.subTest(envar=envar): + with ExitStack() as resources: + env = resources.enter_context(EnvironmentVarGuard()) + env['PYTHONBREAKPOINT'] = envar + mock = resources.enter_context(patch('pdb.set_trace')) + w = resources.enter_context(check_warnings(quiet=True)) + breakpoint() + self.assertEqual( + str(w.message), + f'Ignoring unimportable $PYTHONBREAKPOINT: "{envar}"') + self.assertEqual(w.category, RuntimeWarning) + mock.assert_not_called() + + @unittest.skipUnless(pty, "the pty and signal modules must be available") class PtyTests(unittest.TestCase): """Tests that use a pseudo terminal to guarantee stdin and stdout are diff --git a/Python/bltinmodule.c b/Python/bltinmodule.c index aa40b479f77f91c..c9eafb0db663932 100644 --- a/Python/bltinmodule.c +++ b/Python/bltinmodule.c @@ -418,14 +418,76 @@ builtin_callable(PyObject *module, PyObject *obj) static PyObject * builtin_breakpoint(PyObject *self, PyObject *args, PyObject *keywords) { - PyObject *hook = PySys_GetObject("breakpointhook"); + PyObject *hook = NULL; PyObject *retval = NULL; - - if (hook == NULL) { - PyErr_SetString(PyExc_RuntimeError, "lost sys.breakpointhook"); - return NULL; + char *envar = getenv("PYTHONBREAKPOINT"); + + if (envar != NULL && !strcmp(envar, "0")) { + /* The breakpoint is explicitly no-op'd. */ + Py_RETURN_NONE; + } + if (envar == NULL || strlen(envar) == 0) { + /* The breakpoint is not set, or it is set to the empty string. We + * interpret both conditions to mean "use the default". + */ + hook = PySys_GetObject("breakpointhook"); + if (hook == NULL) { + PyErr_SetString(PyExc_RuntimeError, "lost sys.breakpointhook"); + return NULL; + } + Py_INCREF(hook); + } + else { + /* We can't touch the value returned by getenv(). */ + char *last_dot = strrchr(envar, '.'); + char *attrname = NULL; + PyObject *modulepath = NULL; + PyObject *fromlist = NULL; + PyObject *module = NULL; + + if (last_dot == NULL) { + /* Set the breakpoint to a built-in, e.g. PYTHONBREAKPOINT=int */ + modulepath = PyUnicode_FromString("builtins"); + attrname = envar; + } + else { + /* If any other environment variable value produces an + * unimportable path, warn and ignore. + */ + /* Split on the last dot; */ + modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar); + attrname = last_dot + 1; + } + if (modulepath == NULL) { + return NULL; + } + fromlist = Py_BuildValue("(s)", attrname); + if (fromlist == NULL) { + Py_DECREF(modulepath); + return NULL; + } + module = PyImport_ImportModuleLevelObject( + modulepath, NULL, NULL, fromlist, 0); + Py_DECREF(modulepath); + Py_DECREF(fromlist); + + if (module != NULL) { + hook = PyObject_GetAttrString(module, attrname); + Py_DECREF(module); + } + if (hook == NULL) { + PyErr_Clear(); + int status = PyErr_WarnFormat( + PyExc_RuntimeWarning, 0, + "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar); + if (status == 0) { + /* The warning was (probably) issued. */ + Py_RETURN_NONE; + } + /* Printing the warning raised an exception. */ + return NULL; + } } - Py_INCREF(hook); retval = PyObject_Call(hook, args, keywords); Py_DECREF(hook); return retval; From ed410062314a9abdce48a49c171a4a300040f756 Mon Sep 17 00:00:00 2001 From: Barry Warsaw Date: Mon, 11 Sep 2017 21:39:31 -0700 Subject: [PATCH 17/27] $PYTHONBREAKPOINT processing moved to sys.breakpointhook() --- Python/bltinmodule.c | 77 ++++---------------------------------------- Python/sysmodule.c | 62 +++++++++++++++++++++++++++++------ 2 files changed, 60 insertions(+), 79 deletions(-) diff --git a/Python/bltinmodule.c b/Python/bltinmodule.c index c9eafb0db663932..0c4cd94b44e680e 100644 --- a/Python/bltinmodule.c +++ b/Python/bltinmodule.c @@ -418,77 +418,14 @@ builtin_callable(PyObject *module, PyObject *obj) static PyObject * builtin_breakpoint(PyObject *self, PyObject *args, PyObject *keywords) { - PyObject *hook = NULL; - PyObject *retval = NULL; - char *envar = getenv("PYTHONBREAKPOINT"); - - if (envar != NULL && !strcmp(envar, "0")) { - /* The breakpoint is explicitly no-op'd. */ - Py_RETURN_NONE; - } - if (envar == NULL || strlen(envar) == 0) { - /* The breakpoint is not set, or it is set to the empty string. We - * interpret both conditions to mean "use the default". - */ - hook = PySys_GetObject("breakpointhook"); - if (hook == NULL) { - PyErr_SetString(PyExc_RuntimeError, "lost sys.breakpointhook"); - return NULL; - } - Py_INCREF(hook); - } - else { - /* We can't touch the value returned by getenv(). */ - char *last_dot = strrchr(envar, '.'); - char *attrname = NULL; - PyObject *modulepath = NULL; - PyObject *fromlist = NULL; - PyObject *module = NULL; - - if (last_dot == NULL) { - /* Set the breakpoint to a built-in, e.g. PYTHONBREAKPOINT=int */ - modulepath = PyUnicode_FromString("builtins"); - attrname = envar; - } - else { - /* If any other environment variable value produces an - * unimportable path, warn and ignore. - */ - /* Split on the last dot; */ - modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar); - attrname = last_dot + 1; - } - if (modulepath == NULL) { - return NULL; - } - fromlist = Py_BuildValue("(s)", attrname); - if (fromlist == NULL) { - Py_DECREF(modulepath); - return NULL; - } - module = PyImport_ImportModuleLevelObject( - modulepath, NULL, NULL, fromlist, 0); - Py_DECREF(modulepath); - Py_DECREF(fromlist); - - if (module != NULL) { - hook = PyObject_GetAttrString(module, attrname); - Py_DECREF(module); - } - if (hook == NULL) { - PyErr_Clear(); - int status = PyErr_WarnFormat( - PyExc_RuntimeWarning, 0, - "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar); - if (status == 0) { - /* The warning was (probably) issued. */ - Py_RETURN_NONE; - } - /* Printing the warning raised an exception. */ - return NULL; - } + PyObject *hook = PySys_GetObject("breakpointhook"); + + if (hook == NULL) { + PyErr_SetString(PyExc_RuntimeError, "lost sys.breakpointhook"); + return NULL; } - retval = PyObject_Call(hook, args, keywords); + Py_INCREF(hook); + PyObject *retval = PyObject_Call(hook, args, keywords); Py_DECREF(hook); return retval; } diff --git a/Python/sysmodule.c b/Python/sysmodule.c index 0e1d8950da34a6a..7a13cfe46f8b124 100644 --- a/Python/sysmodule.c +++ b/Python/sysmodule.c @@ -97,20 +97,64 @@ PySys_SetObject(const char *name, PyObject *v) static PyObject * sys_breakpointhook(PyObject *self, PyObject *noargs) { - PyObject *pdb = PyImport_ImportModule("pdb"); - PyObject *set_trace = NULL; - PyObject *retval = NULL; + char *envar = getenv("PYTHONBREAKPOINT"); - if (pdb == NULL) { + if (envar == NULL || strlen(envar) == 0) { + envar = "pdb.set_trace"; + } + else if (!strcmp(envar, "0")) { + /* The breakpoint is explicitly no-op'd. */ + Py_RETURN_NONE; + } + char *last_dot = strrchr(envar, '.'); + char *attrname = NULL; + PyObject *modulepath = NULL; + + if (last_dot == NULL) { + /* The breakpoint is a built-in, e.g. PYTHONBREAKPOINT=int */ + modulepath = PyUnicode_FromString("builtins"); + attrname = envar; + } + else { + /* Split on the last dot; */ + modulepath = PyUnicode_FromStringAndSize(envar, last_dot - envar); + attrname = last_dot + 1; + } + if (modulepath == NULL) { return NULL; } - set_trace = PyObject_GetAttrString(pdb, "set_trace"); - Py_DECREF(pdb); - if (set_trace == NULL) { + + PyObject *fromlist = Py_BuildValue("(s)", attrname); + if (fromlist == NULL) { + Py_DECREF(modulepath); + return NULL; + } + PyObject *module = PyImport_ImportModuleLevelObject( + modulepath, NULL, NULL, fromlist, 0); + Py_DECREF(modulepath); + Py_DECREF(fromlist); + + if (module == NULL) { + return NULL; + } + + PyObject *hook = PyObject_GetAttrString(module, attrname); + Py_DECREF(module); + + if (hook == NULL) { + PyErr_Clear(); + int status = PyErr_WarnFormat( + PyExc_RuntimeWarning, 0, + "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar); + if (status == 0) { + /* The warning was (probably) issued. */ + Py_RETURN_NONE; + } + /* Printing the warning raised an exception. */ return NULL; } - retval = PyObject_CallObject(set_trace, NULL); - Py_DECREF(set_trace); + PyObject *retval = PyObject_CallObject(hook, NULL); + Py_DECREF(hook); return retval; } From b84a018f6f50dd690263674130ff2381cb10c105 Mon Sep 17 00:00:00 2001 From: Barry Warsaw Date: Mon, 11 Sep 2017 21:59:49 -0700 Subject: [PATCH 18/27] Accept *args, **kws --- Python/sysmodule.c | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/Python/sysmodule.c b/Python/sysmodule.c index 7a13cfe46f8b124..96c28d2acced2bf 100644 --- a/Python/sysmodule.c +++ b/Python/sysmodule.c @@ -95,7 +95,7 @@ PySys_SetObject(const char *name, PyObject *v) } static PyObject * -sys_breakpointhook(PyObject *self, PyObject *noargs) +sys_breakpointhook(PyObject *self, PyObject *args, PyObject *keywords) { char *envar = getenv("PYTHONBREAKPOINT"); @@ -153,7 +153,7 @@ sys_breakpointhook(PyObject *self, PyObject *noargs) /* Printing the warning raised an exception. */ return NULL; } - PyObject *retval = PyObject_CallObject(hook, NULL); + PyObject *retval = PyObject_Call(hook, args, keywords); Py_DECREF(hook); return retval; } @@ -1432,7 +1432,8 @@ sys_getandroidapilevel(PyObject *self) static PyMethodDef sys_methods[] = { /* Might as well keep this in alphabetic order */ - {"breakpointhook", sys_breakpointhook, METH_NOARGS, breakpointhook_doc}, + {"breakpointhook", (PyCFunction)sys_breakpointhook, + METH_VARARGS | METH_KEYWORDS, breakpointhook_doc}, {"callstats", (PyCFunction)sys_callstats, METH_NOARGS, callstats_doc}, {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS, From cf9e7acf18ea7652b48a2090ac4af79a2cf0555f Mon Sep 17 00:00:00 2001 From: Barry Warsaw Date: Tue, 12 Sep 2017 01:28:27 -0400 Subject: [PATCH 19/27] Add a test and fix some behavior. --- Lib/test/test_builtin.py | 12 ++++++++++++ Python/sysmodule.c | 26 +++++++++++++++----------- 2 files changed, 27 insertions(+), 11 deletions(-) diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py index aea42c3b3126691..af0ced55044718f 100644 --- a/Lib/test/test_builtin.py +++ b/Lib/test/test_builtin.py @@ -1620,6 +1620,18 @@ def test_envar_unimportable(self): self.assertEqual(w.category, RuntimeWarning) mock.assert_not_called() + def test_envar_ignored_when_hook_is_set(self): + with ExitStack() as resources: + env = resources.enter_context(EnvironmentVarGuard()) + env['PYTHONBREAKPOINT'] = 'sys.exit' + mock = resources.enter_context(patch('sys.exit')) + try: + sys.breakpointhook = int + breakpoint() + finally: + sys.breakpointhook = sys.__breakpointhook__ + mock.assert_not_called() + @unittest.skipUnless(pty, "the pty and signal modules must be available") class PtyTests(unittest.TestCase): diff --git a/Python/sysmodule.c b/Python/sysmodule.c index 47b42caf9a8b0cc..b9b878e714e34d4 100644 --- a/Python/sysmodule.c +++ b/Python/sysmodule.c @@ -137,27 +137,31 @@ sys_breakpointhook(PyObject *self, PyObject *args, PyObject *keywords) Py_DECREF(fromlist); if (module == NULL) { - return NULL; + goto error; } PyObject *hook = PyObject_GetAttrString(module, attrname); Py_DECREF(module); if (hook == NULL) { - PyErr_Clear(); - int status = PyErr_WarnFormat( - PyExc_RuntimeWarning, 0, - "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar); - if (status == 0) { - /* The warning was (probably) issued. */ - Py_RETURN_NONE; - } - /* Printing the warning raised an exception. */ - return NULL; + goto error; } PyObject *retval = PyObject_Call(hook, args, keywords); Py_DECREF(hook); return retval; + + error: + /* If any of the imports went wrong, then warn and ignore. */ + PyErr_Clear(); + int status = PyErr_WarnFormat( + PyExc_RuntimeWarning, 0, + "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar); + if (status == 0) { + /* The warning was (probably) issued. */ + Py_RETURN_NONE; + } + /* Printing the warning raised an exception. */ + return NULL; } PyDoc_STRVAR(breakpointhook_doc, From b5c23935f3b7211d84748dc410e9d7cb4c0eed75 Mon Sep 17 00:00:00 2001 From: Barry Warsaw Date: Tue, 12 Sep 2017 21:36:46 -0700 Subject: [PATCH 20/27] $PYTHONBREAKPOINT docs. --- Doc/library/sys.rst | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/Doc/library/sys.rst b/Doc/library/sys.rst index e08dbd1144d6e98..bf672131140323c 100644 --- a/Doc/library/sys.rst +++ b/Doc/library/sys.rst @@ -122,6 +122,25 @@ always available. its ``*args`` and ``**kws`` straight through. Whatever ``breakpointhooks()`` returns is returned from ``breakpoint()``. + The default implementation first consults the environment variable + ``$PYTHONBREAKPOINT``. If that is set to ``"0"`` then this function + returns immediately; i.e. it is a no-op. If the environment variable is + not set, or is set to the empty string, ``pdb.set_trace()`` is called. + Otherwise this variable should name a function to run, using Python's + dotted-import nomenclature, e.g. ``package.subpackage.module.function``. + In this case, ``package.subpackage.module`` would be imported and the + resulting module must have a callable named ``function()``. This is run, + passing in ``*args`` and ``**kws``, and whatever ``function()`` returns, + ``sys.breakpointhook()`` returns to the built-in :func:`breakpoint` + function. + + Note that if anything goes wrong while importing the callable named by + ``$PYTHONBREAKPOINT``, a :exc:`RuntimeWarning` is reported and the + breakpoint is ignored. + + Also note that if ``sys.breakpointhook()`` is overridden programmatically, + ``$PYTHONBREAKPOINT`` is *not* consulted. + .. versionadded:: 3.7 .. function:: _debugmallocstats() From 50c3e40501c42a30274822db128c2712a485527a Mon Sep 17 00:00:00 2001 From: Barry Warsaw Date: Mon, 2 Oct 2017 20:20:04 -0400 Subject: [PATCH 21/27] Add a What's New. --- Doc/whatsnew/3.7.rst | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/Doc/whatsnew/3.7.rst b/Doc/whatsnew/3.7.rst index 845ed643f97b5bf..8aea2d0aba2491d 100644 --- a/Doc/whatsnew/3.7.rst +++ b/Doc/whatsnew/3.7.rst @@ -107,6 +107,25 @@ locale remains active when the core interpreter is initialized. :pep:`538` -- Coercing the legacy C locale to a UTF-8 based locale PEP written and implemented by Nick Coghlan. +.. _whatsnew37-pep553: + +PEP 553: Built-in breakpoint() +------------------------------ + +:pep:`553` describes a new built-in called ``breakpoint()`` which makes it +easy and consistent to enter the Python debugger. Built-in ``breakpoint()`` +calls ``sys.breakpointhook()``. By default, this latter imports ``pdb`` and +then calls ``pdb.set_trace()``, but by binding ``sys.breakpointhook()`` to the +function of your choosing, ``breakpoint()`` can enter any debugger. Or, the +environment variable :envvar:`PYTHONBREAKPOINT` can be set to the callable of +your debugger of choice. Set ``PYTHONBREAKPOINT=0`` to completely disable +built-in ``breakpoint()``. + +.. seealso:: + + :pep:`553` -- Built-in breakpoint() + PEP written and implemented by Barry Warsaw + Other Language Changes ====================== From 0d2fae5bd00fa9a94eadb2ae9371686e9ccd3aa3 Mon Sep 17 00:00:00 2001 From: Barry Warsaw Date: Wed, 4 Oct 2017 10:55:50 -0400 Subject: [PATCH 22/27] Several fixes addressing review comments. The biggest change is to use a setUp() that ensures a clean slate for the tests, regardless of whether sys.breakpointhook or PYTHONBREAKPOINT is set. --- Doc/library/sys.rst | 6 +- Doc/using/cmdline.rst | 11 ++ Lib/test/test_builtin.py | 105 ++++++++---------- .../2017-09-05-14-19-02.bpo-31353.oGZUeJ.rst | 2 +- 4 files changed, 62 insertions(+), 62 deletions(-) diff --git a/Doc/library/sys.rst b/Doc/library/sys.rst index bf672131140323c..aa7bd477b05a1b8 100644 --- a/Doc/library/sys.rst +++ b/Doc/library/sys.rst @@ -123,7 +123,7 @@ always available. ``breakpointhooks()`` returns is returned from ``breakpoint()``. The default implementation first consults the environment variable - ``$PYTHONBREAKPOINT``. If that is set to ``"0"`` then this function + :envvar:`PYTHONBREAKPOINT`. If that is set to ``"0"`` then this function returns immediately; i.e. it is a no-op. If the environment variable is not set, or is set to the empty string, ``pdb.set_trace()`` is called. Otherwise this variable should name a function to run, using Python's @@ -135,11 +135,11 @@ always available. function. Note that if anything goes wrong while importing the callable named by - ``$PYTHONBREAKPOINT``, a :exc:`RuntimeWarning` is reported and the + :envvar:`PYTHONBREAKPOINT`, a :exc:`RuntimeWarning` is reported and the breakpoint is ignored. Also note that if ``sys.breakpointhook()`` is overridden programmatically, - ``$PYTHONBREAKPOINT`` is *not* consulted. + :envvar:`PYTHONBREAKPOINT` is *not* consulted. .. versionadded:: 3.7 diff --git a/Doc/using/cmdline.rst b/Doc/using/cmdline.rst index 9c1c269d1dffb9d..855b075d5a1fa1e 100644 --- a/Doc/using/cmdline.rst +++ b/Doc/using/cmdline.rst @@ -502,6 +502,17 @@ conflict. :option:`-O` multiple times. +.. envvar:: PYTHONBREAKPOINT + + If this is set, it names a callable using dotted-path notation. The module + containing the callable will be imported and then the callable will be run + by the default implementation of :func:`sys.breakpointhook` which itself is + called by built-in :func:`breakpoint`. If not set, or set to the empty + string, it is equivalent to the value "pdb.set_trace". Setting this to the + string "0" causes the default implementation of :func:`sys.breakpointhook` + to do nothing but return immediately. + + .. envvar:: PYTHONDEBUG If this is set to a non-empty string it is equivalent to specifying the diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py index b16e1bef243a0c3..e2d571cb710cb73 100644 --- a/Lib/test/test_builtin.py +++ b/Lib/test/test_builtin.py @@ -19,7 +19,8 @@ import warnings from contextlib import ExitStack from operator import neg -from test.support import EnvironmentVarGuard, TESTFN, unlink, check_warnings +from test.support import ( + EnvironmentVarGuard, TESTFN, check_warnings, swap_attr, unlink) from test.support.script_helper import assert_python_ok from unittest.mock import patch try: @@ -1518,6 +1519,20 @@ def test_construct_singletons(self): class TestBreakpoint(unittest.TestCase): + def setUp(self): + # These tests require a clean slate environment. For example, if the + # test suite is run with $PYTHONBREAKPOINT set to something else, it + # will mess up these tests. Similarly for sys.breakpointhook. + # Cleaning the slate here means you can't use breakpoint() to debug + # these tests, but I think that's okay. Just use pdb.set_trace() if + # you must. + self.resources = ExitStack() + self.addCleanup(self.resources.close) + self.env = self.resources.enter_context(EnvironmentVarGuard()) + del self.env['PYTHONBREAKPOINT'] + self.resources.enter_context( + swap_attr(sys, 'breakpointhook', sys.__breakpointhook__)) + def test_breakpoint(self): with patch('pdb.set_trace') as mock: breakpoint() @@ -1528,11 +1543,8 @@ def test_breakpoint_with_breakpointhook_set(self): def my_breakpointhook(): nonlocal call_status call_status = 'Called' - try: - sys.breakpointhook = my_breakpointhook - breakpoint() - finally: - sys.breakpointhook = sys.__breakpointhook__ + sys.breakpointhook = my_breakpointhook + breakpoint() self.assertEqual(call_status, 'Called') def test_breakpoint_with_breakpointhook_reset(self): @@ -1540,67 +1552,51 @@ def test_breakpoint_with_breakpointhook_reset(self): def my_breakpointhook(): nonlocal call_status call_status = 'Called' - try: - sys.breakpointhook = my_breakpointhook - breakpoint() - finally: - sys.breakpointhook = sys.__breakpointhook__ + sys.breakpointhook = my_breakpointhook + breakpoint() self.assertEqual(call_status, 'Called') + sys.breakpointhook = sys.__breakpointhook__ with patch('pdb.set_trace') as mock: breakpoint() - mock.assert_called_once() + mock.assert_called_once() def test_breakpoint_with_args_and_keywords(self): call_args = None def my_breakpointhook(*args, **kws): nonlocal call_args call_args = args, kws - try: - sys.breakpointhook = my_breakpointhook - breakpoint(1, 2, 3, four=4, five=5) - finally: - sys.breakpointhook = sys.__breakpointhook__ + sys.breakpointhook = my_breakpointhook + breakpoint(1, 2, 3, four=4, five=5) self.assertEqual(call_args, ((1, 2, 3), dict(four=4, five=5))) def test_breakpoint_with_passthru_error(self): def my_breakpointhook(): pass - try: - sys.breakpointhook = my_breakpointhook - self.assertRaises(TypeError, breakpoint, 1, 2, 3, four=4, five=5) - finally: - sys.breakpointhook = sys.__breakpointhook__ + sys.breakpointhook = my_breakpointhook + self.assertRaises(TypeError, breakpoint, 1, 2, 3, four=4, five=5) def test_envar_good_path_builtin(self): - with ExitStack() as resources: - env = resources.enter_context(EnvironmentVarGuard()) - env['PYTHONBREAKPOINT'] = 'int' - mock = resources.enter_context(patch('builtins.int')) + self.env['PYTHONBREAKPOINT'] = 'int' + with patch('builtins.int') as mock: breakpoint('7') mock.assert_called_once_with('7') def test_envar_good_path_other(self): - with ExitStack() as resources: - env = resources.enter_context(EnvironmentVarGuard()) - env['PYTHONBREAKPOINT'] = 'sys.exit' - mock = resources.enter_context(patch('sys.exit')) + self.env['PYTHONBREAKPOINT'] = 'sys.exit' + with patch('sys.exit') as mock: breakpoint() mock.assert_called_once_with() def test_envar_good_path_noop_0(self): - with ExitStack() as resources: - env = resources.enter_context(EnvironmentVarGuard()) - env['PYTHONBREAKPOINT'] = '0' - mock = resources.enter_context(patch('pdb.set_trace')) + self.env['PYTHONBREAKPOINT'] = '0' + with patch('pdb.set_trace') as mock: breakpoint() mock.assert_not_called() def test_envar_good_path_empty_string(self): # PYTHONBREAKPOINT='' is the same as it not being set. - with ExitStack() as resources: - env = resources.enter_context(EnvironmentVarGuard()) - env['PYTHONBREAKPOINT'] = '' - mock = resources.enter_context(patch('pdb.set_trace')) + self.env['PYTHONBREAKPOINT'] = '' + with patch('pdb.set_trace') as mock: breakpoint() mock.assert_called_once_with() @@ -1611,28 +1607,21 @@ def test_envar_unimportable(self): 'nosuchmodule.nosuchcallable', ): with self.subTest(envar=envar): - with ExitStack() as resources: - env = resources.enter_context(EnvironmentVarGuard()) - env['PYTHONBREAKPOINT'] = envar - mock = resources.enter_context(patch('pdb.set_trace')) - w = resources.enter_context(check_warnings(quiet=True)) - breakpoint() - self.assertEqual( - str(w.message), - f'Ignoring unimportable $PYTHONBREAKPOINT: "{envar}"') - self.assertEqual(w.category, RuntimeWarning) - mock.assert_not_called() + self.env['PYTHONBREAKPOINT'] = envar + mock = self.resources.enter_context(patch('pdb.set_trace')) + w = self.resources.enter_context(check_warnings(quiet=True)) + breakpoint() + self.assertEqual( + str(w.message), + f'Ignoring unimportable $PYTHONBREAKPOINT: "{envar}"') + self.assertEqual(w.category, RuntimeWarning) + mock.assert_not_called() def test_envar_ignored_when_hook_is_set(self): - with ExitStack() as resources: - env = resources.enter_context(EnvironmentVarGuard()) - env['PYTHONBREAKPOINT'] = 'sys.exit' - mock = resources.enter_context(patch('sys.exit')) - try: - sys.breakpointhook = int - breakpoint() - finally: - sys.breakpointhook = sys.__breakpointhook__ + self.env['PYTHONBREAKPOINT'] = 'sys.exit' + with patch('sys.exit') as mock: + sys.breakpointhook = int + breakpoint() mock.assert_not_called() diff --git a/Misc/NEWS.d/next/Core and Builtins/2017-09-05-14-19-02.bpo-31353.oGZUeJ.rst b/Misc/NEWS.d/next/Core and Builtins/2017-09-05-14-19-02.bpo-31353.oGZUeJ.rst index 800e86cf8817a1b..55f81cde8a5d058 100644 --- a/Misc/NEWS.d/next/Core and Builtins/2017-09-05-14-19-02.bpo-31353.oGZUeJ.rst +++ b/Misc/NEWS.d/next/Core and Builtins/2017-09-05-14-19-02.bpo-31353.oGZUeJ.rst @@ -1,4 +1,4 @@ -PEP 553 - Add a new built-in called ``breakpoint()`` which calls +:pep:`553` - Add a new built-in called ``breakpoint()`` which calls ``sys.breakpointhook()``. By default this imports ``pdb`` and calls ``pdb.set_trace()``, but users may override ``sys.breakpointhook()`` to call whatever debugger they want. The original value of the hook is saved in From 1cf3e06d0b34fccdd8b18582431ad1409592e329 Mon Sep 17 00:00:00 2001 From: Barry Warsaw Date: Wed, 4 Oct 2017 20:34:55 -0400 Subject: [PATCH 23/27] Respond to reviewer comments * Improve the readability of the docstring. * Add an assertion. * Use Py_GETENV to obey -E --- Python/bltinmodule.c | 5 ++--- Python/sysmodule.c | 3 ++- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/Python/bltinmodule.c b/Python/bltinmodule.c index cba51106563efe7..e3c265129e5f841 100644 --- a/Python/bltinmodule.c +++ b/Python/bltinmodule.c @@ -440,9 +440,8 @@ builtin_breakpoint(PyObject *self, PyObject *args, PyObject *keywords) PyDoc_STRVAR(breakpoint_doc, "breakpoint(*args, **kws)\n\ \n\ -Call the sys.breakpointhook() function, passing *args and **kws\n\ -through unchanged. sys.breakpointhook() must accept the arguments\n\ -passed.\n\ +Call sys.breakpointhook(*args, **kws). sys.breakpointhook() must accept\n\ +whatever arguments are passed.\n\ \n\ By default, this drops you into the pdb debugger."); diff --git a/Python/sysmodule.c b/Python/sysmodule.c index 717c648a0db695d..e2f95933fb4d96a 100644 --- a/Python/sysmodule.c +++ b/Python/sysmodule.c @@ -99,7 +99,8 @@ PySys_SetObject(const char *name, PyObject *v) static PyObject * sys_breakpointhook(PyObject *self, PyObject *args, PyObject *keywords) { - char *envar = getenv("PYTHONBREAKPOINT"); + assert(!PyErr_Occurred()); + char *envar = Py_GETENV("PYTHONBREAKPOINT"); if (envar == NULL || strlen(envar) == 0) { envar = "pdb.set_trace"; From 6217e908336a4125e6246dca953549b0fdce605f Mon Sep 17 00:00:00 2001 From: Barry Warsaw Date: Wed, 4 Oct 2017 23:16:16 -0400 Subject: [PATCH 24/27] Use METH_FAST and _PyObject_FastCallKeywords() --- Python/bltinmodule.c | 6 +++--- Python/sysmodule.c | 20 ++++++++++---------- 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/Python/bltinmodule.c b/Python/bltinmodule.c index e3c265129e5f841..6215a638c94b71b 100644 --- a/Python/bltinmodule.c +++ b/Python/bltinmodule.c @@ -423,7 +423,7 @@ builtin_callable(PyObject *module, PyObject *obj) } static PyObject * -builtin_breakpoint(PyObject *self, PyObject *args, PyObject *keywords) +builtin_breakpoint(PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *keywords) { PyObject *hook = PySys_GetObject("breakpointhook"); @@ -432,7 +432,7 @@ builtin_breakpoint(PyObject *self, PyObject *args, PyObject *keywords) return NULL; } Py_INCREF(hook); - PyObject *retval = PyObject_Call(hook, args, keywords); + PyObject *retval = _PyObject_FastCallKeywords(hook, args, nargs, keywords); Py_DECREF(hook); return retval; } @@ -2649,7 +2649,7 @@ static PyMethodDef builtin_methods[] = { BUILTIN_ANY_METHODDEF BUILTIN_ASCII_METHODDEF BUILTIN_BIN_METHODDEF - {"breakpoint", (PyCFunction)builtin_breakpoint, METH_VARARGS | METH_KEYWORDS, breakpoint_doc}, + {"breakpoint", (PyCFunction)builtin_breakpoint, METH_FASTCALL | METH_KEYWORDS, breakpoint_doc}, BUILTIN_CALLABLE_METHODDEF BUILTIN_CHR_METHODDEF BUILTIN_COMPILE_METHODDEF diff --git a/Python/sysmodule.c b/Python/sysmodule.c index e2f95933fb4d96a..e38a200c005052c 100644 --- a/Python/sysmodule.c +++ b/Python/sysmodule.c @@ -97,7 +97,7 @@ PySys_SetObject(const char *name, PyObject *v) } static PyObject * -sys_breakpointhook(PyObject *self, PyObject *args, PyObject *keywords) +sys_breakpointhook(PyObject *self, PyObject **args, Py_ssize_t nargs, PyObject *keywords) { assert(!PyErr_Occurred()); char *envar = Py_GETENV("PYTHONBREAKPOINT"); @@ -147,7 +147,7 @@ sys_breakpointhook(PyObject *self, PyObject *args, PyObject *keywords) if (hook == NULL) { goto error; } - PyObject *retval = PyObject_Call(hook, args, keywords); + PyObject *retval = _PyObject_FastCallKeywords(hook, args, nargs, keywords); Py_DECREF(hook); return retval; @@ -157,18 +157,18 @@ sys_breakpointhook(PyObject *self, PyObject *args, PyObject *keywords) int status = PyErr_WarnFormat( PyExc_RuntimeWarning, 0, "Ignoring unimportable $PYTHONBREAKPOINT: \"%s\"", envar); - if (status == 0) { - /* The warning was (probably) issued. */ - Py_RETURN_NONE; + if (status < 0) { + /* Printing the warning raised an exception. */ + return NULL; } - /* Printing the warning raised an exception. */ - return NULL; + /* The warning was (probably) issued. */ + Py_RETURN_NONE; } PyDoc_STRVAR(breakpointhook_doc, -"breakpointhook()\n" +"breakpointhook(*args, **kws)\n" "\n" -"Called when the built-in breakpoint() function is called.\n" +"This hook function is called by built-in breakpoint().\n" ); /* Write repr(o) to sys.stdout using sys.stdout.encoding and 'backslashreplace' @@ -1441,7 +1441,7 @@ sys_getandroidapilevel(PyObject *self) static PyMethodDef sys_methods[] = { /* Might as well keep this in alphabetic order */ {"breakpointhook", (PyCFunction)sys_breakpointhook, - METH_VARARGS | METH_KEYWORDS, breakpointhook_doc}, + METH_FASTCALL | METH_KEYWORDS, breakpointhook_doc}, {"callstats", (PyCFunction)sys_callstats, METH_NOARGS, callstats_doc}, {"_clear_type_cache", sys_clear_type_cache, METH_NOARGS, From 8808367536b8923dfc0897f43f45f01e95d84d5c Mon Sep 17 00:00:00 2001 From: Barry Warsaw Date: Wed, 4 Oct 2017 23:25:46 -0400 Subject: [PATCH 25/27] Use a MagicMock. --- Lib/test/test_builtin.py | 27 ++++++++++----------------- 1 file changed, 10 insertions(+), 17 deletions(-) diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py index e2d571cb710cb73..43fb30d51c22f02 100644 --- a/Lib/test/test_builtin.py +++ b/Lib/test/test_builtin.py @@ -22,7 +22,7 @@ from test.support import ( EnvironmentVarGuard, TESTFN, check_warnings, swap_attr, unlink) from test.support.script_helper import assert_python_ok -from unittest.mock import patch +from unittest.mock import MagicMock, patch try: import pty, signal except ImportError: @@ -1539,35 +1539,28 @@ def test_breakpoint(self): mock.assert_called_once() def test_breakpoint_with_breakpointhook_set(self): - call_status = 'Not called' - def my_breakpointhook(): - nonlocal call_status - call_status = 'Called' + my_breakpointhook = MagicMock() sys.breakpointhook = my_breakpointhook breakpoint() - self.assertEqual(call_status, 'Called') + my_breakpointhook.assert_called_once_with() def test_breakpoint_with_breakpointhook_reset(self): - call_status = 'Not called' - def my_breakpointhook(): - nonlocal call_status - call_status = 'Called' + my_breakpointhook = MagicMock() sys.breakpointhook = my_breakpointhook breakpoint() - self.assertEqual(call_status, 'Called') + my_breakpointhook.assert_called_once_with() + # Reset the hook and it will not be called again. sys.breakpointhook = sys.__breakpointhook__ with patch('pdb.set_trace') as mock: breakpoint() - mock.assert_called_once() + mock.assert_called_once_with() + my_breakpointhook.assert_called_once_with() def test_breakpoint_with_args_and_keywords(self): - call_args = None - def my_breakpointhook(*args, **kws): - nonlocal call_args - call_args = args, kws + my_breakpointhook = MagicMock() sys.breakpointhook = my_breakpointhook breakpoint(1, 2, 3, four=4, five=5) - self.assertEqual(call_args, ((1, 2, 3), dict(four=4, five=5))) + my_breakpointhook.assert_called_once_with(1, 2, 3, four=4, five=5) def test_breakpoint_with_passthru_error(self): def my_breakpointhook(): From 599108dbc6ed75697260bfc904a6b14229ef986e Mon Sep 17 00:00:00 2001 From: Barry Warsaw Date: Thu, 5 Oct 2017 10:35:35 -0400 Subject: [PATCH 26/27] Some tests must be skipped when -E is given --- Lib/test/test_builtin.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py index 43fb30d51c22f02..0a61c054444fc12 100644 --- a/Lib/test/test_builtin.py +++ b/Lib/test/test_builtin.py @@ -1568,18 +1568,21 @@ def my_breakpointhook(): sys.breakpointhook = my_breakpointhook self.assertRaises(TypeError, breakpoint, 1, 2, 3, four=4, five=5) + @unittest.skipIf(sys.flags.ignore_environment, '-E was given') def test_envar_good_path_builtin(self): self.env['PYTHONBREAKPOINT'] = 'int' with patch('builtins.int') as mock: breakpoint('7') mock.assert_called_once_with('7') + @unittest.skipIf(sys.flags.ignore_environment, '-E was given') def test_envar_good_path_other(self): self.env['PYTHONBREAKPOINT'] = 'sys.exit' with patch('sys.exit') as mock: breakpoint() mock.assert_called_once_with() + @unittest.skipIf(sys.flags.ignore_environment, '-E was given') def test_envar_good_path_noop_0(self): self.env['PYTHONBREAKPOINT'] = '0' with patch('pdb.set_trace') as mock: @@ -1593,6 +1596,7 @@ def test_envar_good_path_empty_string(self): breakpoint() mock.assert_called_once_with() + @unittest.skipIf(sys.flags.ignore_environment, '-E was given') def test_envar_unimportable(self): for envar in ( '.', '..', '.foo', 'foo.', '.int', 'int.' From a74f23eef502734c0b73adc54f569668c11418e8 Mon Sep 17 00:00:00 2001 From: Barry Warsaw Date: Thu, 5 Oct 2017 10:37:29 -0400 Subject: [PATCH 27/27] Add a missing versionadded --- Doc/using/cmdline.rst | 1 + 1 file changed, 1 insertion(+) diff --git a/Doc/using/cmdline.rst b/Doc/using/cmdline.rst index 90d733e2d3399d2..a8cdff641e4545b 100644 --- a/Doc/using/cmdline.rst +++ b/Doc/using/cmdline.rst @@ -512,6 +512,7 @@ conflict. string "0" causes the default implementation of :func:`sys.breakpointhook` to do nothing but return immediately. + .. versionadded:: 3.7 .. envvar:: PYTHONDEBUG