Skip to content

Commit d61d997

Browse files
authored
Merge pull request #517 from python/main
Sync Fork from Upstream Repo
2 parents 462a391 + 9c3eaf8 commit d61d997

14 files changed

Lines changed: 505 additions & 51 deletions

File tree

.github/workflows/doc.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ jobs:
4040
- name: 'Build documentation'
4141
run: xvfb-run make -C Doc/ PYTHON=../python SPHINXOPTS="-q -W --keep-going -j4" doctest html
4242
- name: 'Upload'
43-
uses: actions/upload-artifact@v2.2.3
43+
uses: actions/upload-artifact@v2.2.4
4444
with:
4545
name: doc-html
4646
path: Doc/build/html

Doc/c-api/code.rst

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,3 +59,11 @@ bound into a function.
5959
6060
For efficiently iterating over the line numbers in a code object, use `the API described in PEP 626
6161
<https://www.python.org/dev/peps/pep-0626/#out-of-process-debuggers-and-profilers>`_.
62+
63+
.. c:function:: int PyCode_Addr2Location(PyObject *co, int byte_offset, int *start_line, int *start_column, int *end_line, int *end_column)
64+
65+
Sets the passed ``int`` pointers to the source code line and column numbers
66+
for the instruction at ``byte_offset``. Sets the value to ``0`` when
67+
information is not available for any particular element.
68+
69+
Returns ``1`` if the function succeeds and 0 otherwise.

Doc/library/argparse.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -853,6 +853,8 @@ is available in ``argparse`` and adds support for boolean actions such as
853853
>>> parser.parse_args(['--no-foo'])
854854
Namespace(foo=False)
855855

856+
.. versionadded:: 3.9
857+
856858
The recommended way to create a custom action is to extend :class:`Action`,
857859
overriding the ``__call__`` method and optionally the ``__init__`` and
858860
``format_usage`` methods.

Doc/library/importlib.metadata.rst

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,11 @@
88
:synopsis: The implementation of the importlib metadata.
99

1010
.. versionadded:: 3.8
11+
.. versionchanged:: 3.10
12+
``importlib.metadata`` is no longer provisional.
1113

1214
**Source code:** :source:`Lib/importlib/metadata.py`
1315

14-
.. note::
15-
This functionality is provisional and may deviate from the usual
16-
version semantics of the standard library.
17-
1816
``importlib.metadata`` is a library that provides for access to installed
1917
package metadata. Built in part on Python's import system, this library
2018
intends to replace similar functionality in the `entry point

Doc/library/os.path.rst

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -340,6 +340,14 @@ the :mod:`glob` module.)
340340
that contains symbolic links. On Windows, it converts forward slashes to
341341
backward slashes. To normalize case, use :func:`normcase`.
342342

343+
.. note::
344+
On POSIX systems, in accordance with `IEEE Std 1003.1 2013 Edition; 4.13
345+
Pathname Resolution <http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13>`_,
346+
if a pathname begins with exactly two slashes, the first component
347+
following the leading characters may be interpreted in an implementation-defined
348+
manner, although more than two leading characters shall be treated as a
349+
single character.
350+
343351
.. versionchanged:: 3.6
344352
Accepts a :term:`path-like object`.
345353

Doc/library/traceback.rst

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -473,7 +473,7 @@ The output for the example would look similar to this:
473473
['Traceback (most recent call last):\n',
474474
' File "<doctest default[0]>", line 10, in <module>\n lumberjack()\n ^^^^^^^^^^^^\n',
475475
' File "<doctest default[0]>", line 4, in lumberjack\n bright_side_of_death()\n ^^^^^^^^^^^^^^^^^^^^^^\n',
476-
' File "<doctest default[0]>", line 7, in bright_side_of_death\n return tuple()[0]\n ^^^^^^^^^^\n',
476+
' File "<doctest default[0]>", line 7, in bright_side_of_death\n return tuple()[0]\n ~~~~~~~^^^\n',
477477
'IndexError: tuple index out of range\n']
478478
*** extract_tb:
479479
[<FrameSummary file <doctest...>, line 10 in <module>>,
@@ -482,7 +482,7 @@ The output for the example would look similar to this:
482482
*** format_tb:
483483
[' File "<doctest default[0]>", line 10, in <module>\n lumberjack()\n ^^^^^^^^^^^^\n',
484484
' File "<doctest default[0]>", line 4, in lumberjack\n bright_side_of_death()\n ^^^^^^^^^^^^^^^^^^^^^^\n',
485-
' File "<doctest default[0]>", line 7, in bright_side_of_death\n return tuple()[0]\n ^^^^^^^^^^\n']
485+
' File "<doctest default[0]>", line 7, in bright_side_of_death\n return tuple()[0]\n ~~~~~~~^^^\n']
486486
*** tb_lineno: 10
487487

488488

Doc/reference/datamodel.rst

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1015,6 +1015,39 @@ Internal types
10151015
If a code object represents a function, the first item in :attr:`co_consts` is
10161016
the documentation string of the function, or ``None`` if undefined.
10171017

1018+
.. method:: codeobject.co_positions()
1019+
1020+
Returns an iterable over the source code positions of each bytecode
1021+
instruction in the code object.
1022+
1023+
The iterator returns tuples containing the ``(start_line, end_line,
1024+
start_column, end_column)``. The *i-th* tuple corresponds to the
1025+
position of the source code that compiled to the *i-th* instruction.
1026+
Column information is 0-indexed utf-8 byte offsets on the given source
1027+
line.
1028+
1029+
This positional information can be missing. A non-exhaustive lists of
1030+
cases where this may happen:
1031+
1032+
- Running the interpreter with :option:`-X` ``no_debug_ranges``.
1033+
- Loading a pyc file compiled while using :option:`-X` ``no_debug_ranges``.
1034+
- Position tuples corresponding to artificial instructions.
1035+
- Line and column numbers that can't be represented due to
1036+
implementation specific limitations.
1037+
1038+
When this occurs, some or all of the tuple elements can be
1039+
:const:`None`.
1040+
1041+
.. versionadded:: 3.11
1042+
1043+
.. note::
1044+
This feature requires storing column positions in code objects which may
1045+
result in a small increase of disk usage of compiled Python files or
1046+
interpreter memory usage. To avoid storing the extra information and/or
1047+
deactivate printing the extra traceback information, the
1048+
:option:`-X` ``no_debug_ranges`` command line flag or the :envvar:`PYTHONNODEBUGRANGES`
1049+
environment variable can be used.
1050+
10181051
.. _frame-objects:
10191052

10201053
Frame objects

Doc/whatsnew/3.11.rst

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,83 @@ Summary -- Release highlights
7070
New Features
7171
============
7272

73+
.. _whatsnew311-pep657:
74+
75+
Enhanced error locations in tracebacks
76+
--------------------------------------
77+
78+
When printing tracebacks, the interpreter will now point to the exact expression
79+
that caused the error instead of just the line. For example:
80+
81+
.. code-block:: python
82+
83+
Traceback (most recent call last):
84+
File "distance.py", line 11, in <module>
85+
print(manhattan_distance(p1, p2))
86+
^^^^^^^^^^^^^^^^^^^^^^^^^^
87+
File "distance.py", line 6, in manhattan_distance
88+
return abs(point_1.x - point_2.x) + abs(point_1.y - point_2.y)
89+
^^^^^^^^^
90+
AttributeError: 'NoneType' object has no attribute 'x'
91+
92+
Previous versions of the interpreter would point to just the line making it
93+
ambiguous which object was ``None``. These enhanced errors can also be helpful
94+
when dealing with deeply nested dictionary objects and multiple function calls,
95+
96+
.. code-block:: python
97+
98+
Traceback (most recent call last):
99+
File "query.py", line 37, in <module>
100+
magic_arithmetic('foo')
101+
^^^^^^^^^^^^^^^^^^^^^^^
102+
File "query.py", line 18, in magic_arithmetic
103+
return add_counts(x) / 25
104+
^^^^^^^^^^^^^
105+
File "query.py", line 24, in add_counts
106+
return 25 + query_user(user1) + query_user(user2)
107+
^^^^^^^^^^^^^^^^^
108+
File "query.py", line 32, in query_user
109+
return 1 + query_count(db, response['a']['b']['c']['user'], retry=True)
110+
~~~~~~~~~~~~~~~~~~^^^^^
111+
TypeError: 'NoneType' object is not subscriptable
112+
113+
as well as complex arithmetic expressions:
114+
115+
.. code-block:: python
116+
117+
Traceback (most recent call last):
118+
File "calculation.py", line 54, in <module>
119+
result = (x / y / z) * (a / b / c)
120+
~~~~~~^~~
121+
ZeroDivisionError: division by zero
122+
123+
See :pep:`657` for more details. (Contributed by Pablo Galindo, Batuhan Taskaya
124+
and Ammar Askar in :issue:`43950`.)
125+
126+
.. note::
127+
This feature requires storing column positions in code objects which may
128+
result in a small increase of disk usage of compiled Python files or
129+
interpreter memory usage. To avoid storing the extra information and/or
130+
deactivate printing the extra traceback information, the
131+
:option:`-X` ``no_debug_ranges`` command line flag or the :envvar:`PYTHONNODEBUGRANGES`
132+
environment variable can be used.
133+
134+
Column information for code objects
135+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
136+
137+
The information used by the enhanced traceback feature is made available as a
138+
general API that can be used to correlate bytecode instructions with source
139+
code. This information can be retrieved using:
140+
141+
- The :meth:`codeobject.co_positions` method in Python.
142+
- The :c:func:`PyCode_Addr2Location` function in the C-API.
143+
144+
The :option:`-X` ``no_debug_ranges`` option and the environment variable
145+
:envvar:`PYTHONNODEBUGRANGES` can be used to disable this feature.
146+
147+
See :pep:`657` for more details. (Contributed by Pablo Galindo, Batuhan Taskaya
148+
and Ammar Askar in :issue:`43950`.)
149+
73150

74151

75152
Other Language Changes

Lib/posixpath.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -352,6 +352,7 @@ def normpath(path):
352352
initial_slashes = path.startswith(sep)
353353
# POSIX allows one or two initial slashes, but treats three or more
354354
# as single slash.
355+
# (see http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap04.html#tag_04_13)
355356
if (initial_slashes and
356357
path.startswith(sep*2) and not path.startswith(sep*3)):
357358
initial_slashes = 2

Lib/test/test_traceback.py

Lines changed: 80 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,11 @@
1212
requires_debug_ranges, has_no_debug_ranges)
1313
from test.support.os_helper import TESTFN, unlink
1414
from test.support.script_helper import assert_python_ok, assert_python_failure
15-
import textwrap
1615

16+
import os
17+
import textwrap
1718
import traceback
19+
from functools import partial
1820

1921

2022
test_code = namedtuple('code', ['co_filename', 'co_name'])
@@ -406,6 +408,82 @@ def f_with_multiline():
406408
result_lines = self.get_exception(f_with_multiline)
407409
self.assertEqual(result_lines, expected_f.splitlines())
408410

411+
def test_caret_for_binary_operators(self):
412+
def f_with_binary_operator():
413+
divisor = 20
414+
return 10 + divisor / 0 + 30
415+
416+
lineno_f = f_with_binary_operator.__code__.co_firstlineno
417+
expected_error = (
418+
'Traceback (most recent call last):\n'
419+
f' File "{__file__}", line {self.callable_line}, in get_exception\n'
420+
' callable()\n'
421+
' ^^^^^^^^^^\n'
422+
f' File "{__file__}", line {lineno_f+2}, in f_with_binary_operator\n'
423+
' return 10 + divisor / 0 + 30\n'
424+
' ~~~~~~~~^~~\n'
425+
)
426+
result_lines = self.get_exception(f_with_binary_operator)
427+
self.assertEqual(result_lines, expected_error.splitlines())
428+
429+
def test_caret_for_binary_operators_two_char(self):
430+
def f_with_binary_operator():
431+
divisor = 20
432+
return 10 + divisor // 0 + 30
433+
434+
lineno_f = f_with_binary_operator.__code__.co_firstlineno
435+
expected_error = (
436+
'Traceback (most recent call last):\n'
437+
f' File "{__file__}", line {self.callable_line}, in get_exception\n'
438+
' callable()\n'
439+
' ^^^^^^^^^^\n'
440+
f' File "{__file__}", line {lineno_f+2}, in f_with_binary_operator\n'
441+
' return 10 + divisor // 0 + 30\n'
442+
' ~~~~~~~~^^~~\n'
443+
)
444+
result_lines = self.get_exception(f_with_binary_operator)
445+
self.assertEqual(result_lines, expected_error.splitlines())
446+
447+
def test_caret_for_subscript(self):
448+
def f_with_subscript():
449+
some_dict = {'x': {'y': None}}
450+
return some_dict['x']['y']['z']
451+
452+
lineno_f = f_with_subscript.__code__.co_firstlineno
453+
expected_error = (
454+
'Traceback (most recent call last):\n'
455+
f' File "{__file__}", line {self.callable_line}, in get_exception\n'
456+
' callable()\n'
457+
' ^^^^^^^^^^\n'
458+
f' File "{__file__}", line {lineno_f+2}, in f_with_subscript\n'
459+
" return some_dict['x']['y']['z']\n"
460+
' ~~~~~~~~~~~~~~~~~~~^^^^^\n'
461+
)
462+
result_lines = self.get_exception(f_with_subscript)
463+
self.assertEqual(result_lines, expected_error.splitlines())
464+
465+
def test_traceback_specialization_with_syntax_error(self):
466+
bytecode = compile("1 / 0 / 1 / 2\n", TESTFN, "exec")
467+
468+
with open(TESTFN, "w") as file:
469+
# make the file's contents invalid
470+
file.write("1 $ 0 / 1 / 2\n")
471+
self.addCleanup(unlink, TESTFN)
472+
473+
func = partial(exec, bytecode)
474+
result_lines = self.get_exception(func)
475+
476+
lineno_f = bytecode.co_firstlineno
477+
expected_error = (
478+
'Traceback (most recent call last):\n'
479+
f' File "{__file__}", line {self.callable_line}, in get_exception\n'
480+
' callable()\n'
481+
' ^^^^^^^^^^\n'
482+
f' File "{TESTFN}", line {lineno_f}, in <module>\n'
483+
" 1 $ 0 / 1 / 2\n"
484+
' ^^^^^\n'
485+
)
486+
self.assertEqual(result_lines, expected_error.splitlines())
409487

410488
@cpython_only
411489
@requires_debug_ranges()
@@ -1615,7 +1693,7 @@ def f():
16151693
self.assertEqual(
16161694
output.getvalue().split('\n')[-5:],
16171695
[' x/0',
1618-
' ^^^',
1696+
' ~^~',
16191697
' x = 12',
16201698
'ZeroDivisionError: division by zero',
16211699
''])

0 commit comments

Comments
 (0)