Skip to content

Commit 3e35db7

Browse files
committed
gh-136640: Correct the description of AST location attributes
Eight of the types generated from ``Parser/Python.asdl`` carry the ``lineno``/``col_offset``/``end_lineno``/``end_col_offset`` attributes -- ``stmt``, ``expr``, ``excepthandler``, ``arg``, ``keyword``, ``alias``, ``pattern`` and ``type_param`` -- but the documentation named only ``ast.expr`` and ``ast.stmt``. The same block also stated that the end positions are always optional. That holds for the six types that declare them as ``int?`` in the grammar; ``pattern`` and ``type_param`` declare them as ``int``, and compiling a tree whose ``pattern`` or ``type_param`` node is missing ``end_lineno`` raises ``TypeError``. The first paragraph follows the wording approved in GH-136868 and the two review suggestions on it, except that it keeps the original "Instances of": the classes themselves expose nothing, so ``hasattr(ast.Name, 'lineno')`` is false. The cross-reference uses ``:ref:``, matching the rest of the file.
1 parent 6893326 commit 3e35db7

1 file changed

Lines changed: 7 additions & 3 deletions

File tree

‎Doc/library/ast.rst‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -90,17 +90,21 @@ Node classes
9090
end_lineno
9191
end_col_offset
9292

93-
Instances of :class:`ast.expr` and :class:`ast.stmt` subclasses have
93+
Instances of most classes in the :mod:`!ast` module have the
9494
:attr:`lineno`, :attr:`col_offset`, :attr:`end_lineno`, and
95-
:attr:`end_col_offset` attributes. The :attr:`lineno` and :attr:`end_lineno`
95+
:attr:`end_col_offset` attributes, including all subclasses of
96+
:class:`ast.expr`, :class:`ast.stmt` and others (see the abstract grammar
97+
:ref:`above <abstract-grammar>`). The :attr:`lineno` and :attr:`end_lineno`
9698
are the first and last line numbers of source text span (1-indexed so the
9799
first line is line 1) and the :attr:`col_offset` and :attr:`end_col_offset`
98100
are the corresponding UTF-8 byte offsets of the first and last tokens that
99101
generated the node. The UTF-8 offset is recorded because the parser uses
100102
UTF-8 internally.
101103

102104
Note that the end positions are not required by the compiler and are
103-
therefore optional. The end offset is *after* the last symbol, for example
105+
therefore optional, except for :class:`ast.pattern` and
106+
:class:`ast.type_param` nodes, for which the compiler requires them.
107+
The end offset is *after* the last symbol, for example
104108
one can get the source segment of a one-line expression node using
105109
``source_line[node.col_offset : node.end_col_offset]``.
106110

0 commit comments

Comments
 (0)