Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 0 additions & 15 deletions Doc/c-api/arg.rst
Original file line number Diff line number Diff line change
Expand Up @@ -113,18 +113,14 @@ There are three ways strings and buffers can be converted to C:
``z`` (:class:`str` or ``None``) [const char \*]
Like ``s``, but the Python object may also be ``None``, in which case the C
pointer is set to ``NULL``.
It is the same as ``s?`` with the C pointer was initialized to ``NULL``.

``z*`` (:class:`str`, :term:`bytes-like object` or ``None``) [Py_buffer]
Like ``s*``, but the Python object may also be ``None``, in which case the
``buf`` member of the :c:type:`Py_buffer` structure is set to ``NULL``.
It is the same as ``s*?`` with the ``buf`` member of the :c:type:`Py_buffer`
structure was initialized to ``NULL``.

``z#`` (:class:`str`, read-only :term:`bytes-like object` or ``None``) [const char \*, :c:type:`Py_ssize_t`]
Like ``s#``, but the Python object may also be ``None``, in which case the C
pointer is set to ``NULL``.
It is the same as ``s#?`` with the C pointer was initialized to ``NULL``.

``y`` (read-only :term:`bytes-like object`) [const char \*]
This format converts a bytes-like object to a C pointer to a
Expand Down Expand Up @@ -394,17 +390,6 @@ Other objects
Non-tuple sequences are deprecated if *items* contains format units
which store a borrowed buffer or a borrowed reference.

``unit?`` (anything or ``None``) [*matching-variable(s)*]
``?`` modifies the behavior of the preceding format unit.
The C variable(s) corresponding to that parameter should be initialized
to their default value --- when the argument is ``None``,
:c:func:`PyArg_ParseTuple` does not touch the contents of the corresponding
C variable(s).
If the argument is not ``None``, it is parsed according to the specified
format unit.

.. versionadded:: 3.14

A few other characters have a meaning in a format string. These may not occur
inside nested parentheses. They are:

Expand Down
7 changes: 6 additions & 1 deletion Doc/glossary.rst
Original file line number Diff line number Diff line change
Expand Up @@ -462,7 +462,7 @@ Glossary
core and with user code.

f-string
String literals prefixed with ``'f'`` or ``'F'`` are commonly called
String literals prefixed with ``f`` or ``F`` are commonly called
"f-strings" which is short for
:ref:`formatted string literals <f-strings>`. See also :pep:`498`.

Expand Down Expand Up @@ -1322,6 +1322,11 @@ Glossary

See also :term:`borrowed reference`.

t-string
String literals prefixed with ``t`` or ``T`` are commonly called
"t-strings" which is short for
:ref:`template string literals <t-strings>`.

text encoding
A string in Python is a sequence of Unicode code points (in range
``U+0000``--``U+10FFFF``). To store or transfer a string, it needs to be
Expand Down
2 changes: 1 addition & 1 deletion Doc/library/annotationlib.rst
Original file line number Diff line number Diff line change
Expand Up @@ -511,7 +511,7 @@ code execution even with no access to any globals or builtins. For example:

>>> def f(x: (1).__class__.__base__.__subclasses__()[-1].__init__.__builtins__["print"]("Hello world")): pass
...
>>> annotationlib.get_annotations(f, format=annotationlib.Format.SOURCE)
>>> annotationlib.get_annotations(f, format=annotationlib.Format.STRING)
Hello world
{'x': 'None'}

Expand Down
54 changes: 51 additions & 3 deletions Doc/library/ast.rst
Original file line number Diff line number Diff line change
Expand Up @@ -289,9 +289,9 @@ Literals
* ``conversion`` is an integer:

* -1: no formatting
* 115: ``!s`` string formatting
* 114: ``!r`` repr formatting
* 97: ``!a`` ascii formatting
* 115 (``ord('s')``): ``!s`` string formatting
* 114 (``ord('r')``): ``!r`` repr formatting
* 97 (``ord('a')``): ``!a`` ASCII formatting

* ``format_spec`` is a :class:`JoinedStr` node representing the formatting
of the value, or ``None`` if no format was specified. Both
Expand Down Expand Up @@ -325,6 +325,54 @@ Literals
Constant(value='.3')]))]))


.. class:: TemplateStr(values)

A t-string, comprising a series of :class:`Interpolation` and :class:`Constant`
nodes.

.. doctest::

>>> print(ast.dump(ast.parse('t"{name} finished {place:ordinal}"', mode='eval'), indent=4))
Expression(
body=TemplateStr(
values=[
Interpolation(
value=Name(id='name'),
str='name',
conversion=-1),
Constant(value=' finished '),
Interpolation(
value=Name(id='place'),
str='place',
conversion=-1,
format_spec=JoinedStr(
values=[
Constant(value='ordinal')]))]))

.. versionadded:: 3.14


.. class:: Interpolation(value, str, conversion, format_spec)

Node representing a single interpolation field in a t-string.

* ``value`` is any expression node (such as a literal, a variable, or a
function call).
* ``str`` is a constant containing the text of the interpolation expression.
* ``conversion`` is an integer:

* -1: no conversion
* 115: ``!s`` string conversion
* 114: ``!r`` repr conversion
* 97: ``!a`` ascii conversion

* ``format_spec`` is a :class:`JoinedStr` node representing the formatting
of the value, or ``None`` if no format was specified. Both
``conversion`` and ``format_spec`` can be set at the same time.

.. versionadded:: 3.14


.. class:: List(elts, ctx)
Tuple(elts, ctx)

Expand Down
42 changes: 42 additions & 0 deletions Doc/library/dis.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1120,6 +1120,48 @@ iterations of the loop.
.. versionadded:: 3.12


.. opcode:: BUILD_TEMPLATE

Constructs a new :class:`~string.templatelib.Template` from a tuple
of strings and a tuple of interpolations and pushes the resulting instance
onto the stack::

interpolations = STACK.pop()
strings = STACK.pop()
STACK.append(_build_template(strings, interpolations))

.. versionadded:: 3.14


.. opcode:: BUILD_INTERPOLATION (format)

Constructs a new :class:`~string.templatelib.Interpolation` from a
value and its source expression and pushes the resulting instance onto the
stack.

If no conversion or format specification is present, ``format`` is set to
``2``.

If the low bit of ``format`` is set, it indicates that the interpolation
contains a format specification.

If ``format >> 2`` is non-zero, it indicates that the interpolation
contains a conversion. The value of ``format >> 2`` is the conversion type
(``0`` for no conversion, ``1`` for ``!s``, ``2`` for ``!r``, and
``3`` for ``!a``)::

conversion = format >> 2
if format & 1:
format_spec = STACK.pop()
else:
format_spec = None
expression = STACK.pop()
value = STACK.pop()
STACK.append(_build_interpolation(value, expression, conversion, format_spec))

.. versionadded:: 3.14


.. opcode:: BUILD_TUPLE (count)

Creates a tuple consuming *count* items from the stack, and pushes the
Expand Down
18 changes: 9 additions & 9 deletions Doc/library/os.path.rst
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ the :mod:`glob` module.)
Any iterable can now be passed, rather than just sequences.


.. function:: commonprefix(list)
.. function:: commonprefix(list, /)

Return the longest path prefix (taken character-by-character) that is a
prefix of all paths in *list*. If *list* is empty, return the empty string
Expand Down Expand Up @@ -199,14 +199,14 @@ the :mod:`glob` module.)
Accepts a :term:`path-like object`.


.. function:: getatime(path)
.. function:: getatime(path, /)

Return the time of last access of *path*. The return value is a floating-point number giving
the number of seconds since the epoch (see the :mod:`time` module). Raise
:exc:`OSError` if the file does not exist or is inaccessible.


.. function:: getmtime(path)
.. function:: getmtime(path, /)

Return the time of last modification of *path*. The return value is a floating-point number
giving the number of seconds since the epoch (see the :mod:`time` module).
Expand All @@ -216,7 +216,7 @@ the :mod:`glob` module.)
Accepts a :term:`path-like object`.


.. function:: getctime(path)
.. function:: getctime(path, /)

Return the system's ctime which, on some systems (like Unix) is the time of the
last metadata change, and, on others (like Windows), is the creation time for *path*.
Expand All @@ -228,7 +228,7 @@ the :mod:`glob` module.)
Accepts a :term:`path-like object`.


.. function:: getsize(path)
.. function:: getsize(path, /)

Return the size, in bytes, of *path*. Raise :exc:`OSError` if the file does
not exist or is inaccessible.
Expand Down Expand Up @@ -351,7 +351,7 @@ the :mod:`glob` module.)
.. versionadded:: 3.13


.. function:: join(path, *paths)
.. function:: join(path, /, *paths)

Join one or more path segments intelligently. The return value is the
concatenation of *path* and all members of *\*paths*, with exactly one
Expand Down Expand Up @@ -402,7 +402,7 @@ the :mod:`glob` module.)
Accepts a :term:`path-like object`.


.. function:: realpath(path, *, strict=False)
.. function:: realpath(path, /, *, strict=False)

Return the canonical path of the specified filename, eliminating any symbolic
links encountered in the path (if they are supported by the operating
Expand Down Expand Up @@ -471,7 +471,7 @@ the :mod:`glob` module.)
Accepts a :term:`path-like object`.


.. function:: samefile(path1, path2)
.. function:: samefile(path1, path2, /)

Return ``True`` if both pathname arguments refer to the same file or directory.
This is determined by the device number and i-node number and raises an
Expand All @@ -498,7 +498,7 @@ the :mod:`glob` module.)
Accepts a :term:`path-like object`.


.. function:: samestat(stat1, stat2)
.. function:: samestat(stat1, stat2, /)

Return ``True`` if the stat tuples *stat1* and *stat2* refer to the same file.
These structures may have been returned by :func:`os.fstat`,
Expand Down
6 changes: 3 additions & 3 deletions Doc/library/stdtypes.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2675,9 +2675,9 @@ For example:
lead to a number of common errors (such as failing to display tuples and
dictionaries correctly). Using the newer :ref:`formatted string literals
<f-strings>`, the :meth:`str.format` interface, or :ref:`template strings
<template-strings>` may help avoid these errors. Each of these
alternatives provides their own trade-offs and benefits of simplicity,
flexibility, and/or extensibility.
($-strings) <template-strings-pep292>` may help avoid these errors.
Each of these alternatives provides their own trade-offs and benefits of
simplicity, flexibility, and/or extensibility.

String objects have one unique built-in operation: the ``%`` operator (modulo).
This is also known as the string *formatting* or *interpolation* operator.
Expand Down
25 changes: 19 additions & 6 deletions Doc/library/string.rst
Original file line number Diff line number Diff line change
Expand Up @@ -198,8 +198,9 @@ Format String Syntax
The :meth:`str.format` method and the :class:`Formatter` class share the same
syntax for format strings (although in the case of :class:`Formatter`,
subclasses can define their own format string syntax). The syntax is
related to that of :ref:`formatted string literals <f-strings>`, but it is
less sophisticated and, in particular, does not support arbitrary expressions.
related to that of :ref:`formatted string literals <f-strings>` and
:ref:`template string literals <t-strings>`, but it is less sophisticated
and, in particular, does not support arbitrary expressions.

.. index::
single: {} (curly brackets); in string formatting
Expand Down Expand Up @@ -264,6 +265,8 @@ Some simple format string examples::
"Weight in tons {0.weight}" # 'weight' attribute of first positional arg
"Units destroyed: {players[0]}" # First element of keyword argument 'players'.

.. _formatstrings-conversion:

The *conversion* field causes a type coercion before formatting. Normally, the
job of formatting a value is done by the :meth:`~object.__format__` method of the value
itself. However, in some cases it is desirable to force a type to be formatted
Expand Down Expand Up @@ -306,7 +309,7 @@ Format Specification Mini-Language

"Format specifications" are used within replacement fields contained within a
format string to define how individual values are presented (see
:ref:`formatstrings` and :ref:`f-strings`).
:ref:`formatstrings`, :ref:`f-strings`, and :ref:`t-strings`).
They can also be passed directly to the built-in
:func:`format` function. Each formattable type may define how the format
specification is to be interpreted.
Expand Down Expand Up @@ -789,10 +792,20 @@ Nesting arguments and more complex examples::



.. _template-strings:
.. _template-strings-pep292:

Template strings
----------------
Template strings ($-strings)
----------------------------

.. note::

The feature described here was introduced in Python 2.4. It is unrelated
to, and should not be confused with, the newer
:ref:`template strings <template-strings>` and
:ref:`t-string literal syntax <t-strings>` introduced in Python 3.14.
T-string literals evaluate to instances of a different
:class:`~string.templatelib.Template` class, found in the
:mod:`string.templatelib` module.

Template strings provide simpler string substitutions as described in
:pep:`292`. A primary use case for template strings is for
Expand Down
Loading
Loading