Skip to content
Open
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
9 changes: 5 additions & 4 deletions Doc/library/ast.rst
Original file line number Diff line number Diff line change
Expand Up @@ -613,10 +613,10 @@ Expressions

.. class:: BoolOp(op, values)

A boolean operation, 'or' or 'and'. ``op`` is :class:`Or` or :class:`And`.
``values`` are the values involved. Consecutive operations with the same
operator, such as ``a or b or c``, are collapsed into one node with several
values.
A boolean operation, 'and', 'or' or '??'. ``op`` is :class:`And`,
:class:`Or` or :class:`Coalesce`. ``values`` are the values involved.
Consecutive operations with the same operator, such as ``a or b or c``,
are collapsed into one node with several values.

This doesn't include ``not``, which is a :class:`UnaryOp`.

Expand All @@ -633,6 +633,7 @@ Expressions

.. class:: And
Or
Coalesce

Boolean operator tokens.

Expand Down
8 changes: 8 additions & 0 deletions Doc/library/dis.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2034,6 +2034,14 @@ but are replaced by real opcodes or removed before bytecode is generated.
Conditional jumps which do not impact the stack. Replaced by the sequence
``COPY 1``, ``TO_BOOL``, ``POP_JUMP_IF_TRUE/FALSE``.

.. opcode:: JUMP_IF_NONE
JUMP_IF_NOT_NONE

Conditional jumps which do not impact the stack. Replaced by the sequence
``COPY 1``, ``POP_JUMP_IF_NONE/NOT_NONE``.

.. versionadded:: 3.16

.. opcode:: LOAD_CLOSURE (i)

Pushes a reference to the cell contained in slot ``i`` of the "fast locals"
Expand Down
2 changes: 2 additions & 0 deletions Doc/library/token-list.inc

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 13 additions & 0 deletions Doc/reference/expressions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2310,6 +2310,7 @@ truth value. [#]_
.. _and:
.. _or:
.. _not:
.. _??:

Boolean operations
==================
Expand All @@ -2319,6 +2320,7 @@ Boolean operations
pair: Boolean; operation

.. productionlist:: python-grammar
coalesce_test: `or_test` | `coalesce_test` "??" `or_test`
or_test: `and_test` | `or_test` "or" `and_test`
and_test: `not_test` | `and_test` "and" `not_test`
not_test: `comparison` | "not" `not_test`
Expand All @@ -2345,6 +2347,12 @@ returned; otherwise, *y* is evaluated and the resulting value is returned.
The expression ``x or y`` first evaluates *x*; if *x* is true, its value is
returned; otherwise, *y* is evaluated and the resulting value is returned.

.. index:: pair: operator; ??

The expression ``x ?? y`` first evaluates *x*; if *x* is ``not None``, its
value is returned; otherwise, *y* is evaluated and the resulting value is
returned.

Note that neither :keyword:`and` nor :keyword:`or` restrict the value and type
they return to ``False`` and ``True``, but rather return the last evaluated
argument. This is sometimes useful, e.g., if ``s`` is a string that should be
Expand All @@ -2353,6 +2361,9 @@ the desired value. Because :keyword:`not` has to create a new value, it
returns a boolean value regardless of the type of its argument
(for example, ``not 'foo'`` produces ``False`` rather than ``''``.)

.. versionadded:: 3.16
Added the ``None``-coalese operator :keyword:`??`.


.. index::
single: := (colon equals)
Expand Down Expand Up @@ -2602,6 +2613,8 @@ precedence and have a left-to-right chaining feature as described in the
+-----------------------------------------------+-------------------------------------+
| :keyword:`or` | Boolean OR |
+-----------------------------------------------+-------------------------------------+
| :keyword:`??` | Boolean COALESCE |
+-----------------------------------------------+-------------------------------------+
| :keyword:`if <if_expr>` -- :keyword:`!else` | Conditional expression |
+-----------------------------------------------+-------------------------------------+
| :keyword:`lambda` | Lambda expression |
Expand Down
15 changes: 15 additions & 0 deletions Doc/whatsnew/3.16.rst
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ Summary -- Release highlights
.. This section singles out the most important changes in Python 3.16.
Brevity is key.

* :pep:`824`: :ref:`None-coalesce operator <whatnew316-none-coalesce-operator>`.
* :ref:`Set operations and Unicode properties in regular expressions
<whatsnew316-re-set-operations-and-unicode-properties>`.
* :ref:`Encrypted Client Hello support in ssl <whatsnew316-ssl-ech>`.
Expand All @@ -76,6 +77,20 @@ Summary -- Release highlights
New features
============

.. _whatnew316-none-coalesce-operator:

:pep:`824`: ``None``-coalesce operator
--------------------------------------

A new boolean operator :keyword:`??` is added. For the expression ``x ?? y``
it first evaluates *x*; if *x* is ``not None``, its value is returned;
otherwise, *y* is evaluated and the resulting value is returned.

(Contributed by Marc Mueller in :gh:`162540`)

.. seealso:: :pep:`824` for further details.


.. _whatsnew316-improved-error-messages:

Improved error messages
Expand Down
1 change: 1 addition & 0 deletions Grammar/Tokens
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ RARROW '->'
ELLIPSIS '...'
COLONEQUAL ':='
EXCLAMATION '!'
COALESCE '??'

OP
TYPE_IGNORE
Expand Down
16 changes: 8 additions & 8 deletions Grammar/invalid.gram
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ invalid_kwarg:

# IMPORTANT: Note that the "_without_invalid" suffix causes the rule to not call invalid rules under it
expression_without_invalid[expr_ty]:
| a=disjunction 'if' b=disjunction 'else' c=expression { _PyAST_IfExp(b, a, c, EXTRA) }
| disjunction
| a=coalesce 'if' b=coalesce 'else' c=expression { _PyAST_IfExp(b, a, c, EXTRA) }
| coalesce
| lambdef
invalid_legacy_expression:
| a=NAME !'(' b=star_expressions {
Expand All @@ -66,22 +66,22 @@ invalid_expression:
"invalid syntax. Is this intended to be part of the string?") }
# !(NAME STRING) is not matched so we don't show this error with some invalid string prefixes like: kf"dsfsdf"
# Soft keywords need to also be ignored because they can be parsed as NAME NAME
| !(NAME STRING | SOFT_KEYWORD) a=disjunction b=expression_without_invalid {
| !(NAME STRING | SOFT_KEYWORD) a=coalesce b=expression_without_invalid {
_PyPegen_raise_error_for_missing_comma(p, a, b) }
| a=disjunction 'if' b=disjunction !('else'|':') { RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "expected 'else' after 'if' expression") }
| a=disjunction 'if' b=disjunction 'else' !expression {
| a=coalesce 'if' b=coalesce !('else'|':') { RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "expected 'else' after 'if' expression") }
| a=coalesce 'if' b=coalesce 'else' !expression {
RAISE_SYNTAX_ERROR_ON_NEXT_TOKEN("expected expression after 'else', but statement is given") }
| a[stmt_ty]=(pass_stmt|break_stmt|continue_stmt) 'if' b=disjunction 'else' c=simple_stmt {
| a[stmt_ty]=(pass_stmt|break_stmt|continue_stmt) 'if' b=coalesce 'else' c=simple_stmt {
RAISE_SYNTAX_ERROR_KNOWN_LOCATION (a, "expected expression before 'if', but statement is given") }
| a='lambda' [lambda_params] b=':' &FSTRING_MIDDLE {
RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "f-string: lambda expressions are not allowed without parentheses") }
| a='lambda' [lambda_params] b=':' &TSTRING_MIDDLE {
RAISE_SYNTAX_ERROR_KNOWN_RANGE(a, b, "t-string: lambda expressions are not allowed without parentheses") }

invalid_if_expression:
| disjunction 'if' b=disjunction 'else' a='*' {
| coalesce 'if' b=coalesce 'else' a='*' {
RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "cannot unpack only part of a conditional expression") }
| disjunction 'if' b=disjunction 'else' a='**' {
| coalesce 'if' b=coalesce 'else' a='**' {
RAISE_SYNTAX_ERROR_KNOWN_LOCATION(a, "cannot use dict unpacking on only part of a conditional expression") }

invalid_named_expression(memo):
Expand Down
19 changes: 14 additions & 5 deletions Grammar/python.gram
Original file line number Diff line number Diff line change
Expand Up @@ -721,11 +721,11 @@ expression[expr_ty] (memo):
| invalid_expression
| invalid_legacy_expression
| if_expression
| disjunction
| coalesce
| lambdef

if_expression[expr_ty]:
| a=disjunction 'if' b=disjunction 'else' c=expression { _PyAST_IfExp(b, a, c, EXTRA) }
| a=coalesce 'if' b=coalesce 'else' c=expression { _PyAST_IfExp(b, a, c, EXTRA) }

yield_expr[expr_ty]:
| 'yield' 'from' a=expression { _PyAST_YieldFrom(a, EXTRA) }
Expand Down Expand Up @@ -757,7 +757,16 @@ named_expression[expr_ty]:
| invalid_named_expression
| expression !':='

disjunction[expr_ty] (memo, fastpath=_PyPegen_atom_fast_path):
coalesce[expr_ty] (memo, fastpath=_PyPegen_atom_fast_path):
| a=disjunction b=('??' c=disjunction { c })+ { CHECK_VERSION(
expr_ty, 16, "Coalesce expressions are",
_PyAST_BoolOp(
Coalesce,
CHECK(asdl_expr_seq*, _PyPegen_seq_insert_in_front(p, a, b)),
EXTRA)) }
| disjunction

disjunction[expr_ty] (memo):
| a=conjunction b=('or' c=conjunction { c })+ { _PyAST_BoolOp(
Or,
CHECK(asdl_expr_seq*, _PyPegen_seq_insert_in_front(p, a, b)),
Expand Down Expand Up @@ -1042,9 +1051,9 @@ for_if_clauses[asdl_comprehension_seq*]:
| a[asdl_comprehension_seq*]=for_if_clause+ { a }

for_if_clause[comprehension_ty]:
| 'async' 'for' a=star_targets 'in' ~ b=disjunction c[asdl_expr_seq*]=('if' z=disjunction { z })* {
| 'async' 'for' a=star_targets 'in' ~ b=coalesce c[asdl_expr_seq*]=('if' z=coalesce { z })* {
CHECK_VERSION(comprehension_ty, 6, "Async comprehensions are", _PyAST_comprehension(a, b, c, 1, p->arena)) }
| 'for' a=star_targets 'in' ~ b=disjunction c[asdl_expr_seq*]=('if' z=disjunction { z })* {
| 'for' a=star_targets 'in' ~ b=coalesce c[asdl_expr_seq*]=('if' z=coalesce { z })* {
_PyAST_comprehension(a, b, c, 0, p->arena) }
| invalid_for_if_clause
| invalid_for_target
Expand Down
2 changes: 1 addition & 1 deletion Include/internal/pycore_ast.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Include/internal/pycore_ast_state.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion Include/internal/pycore_magic_number.h
Original file line number Diff line number Diff line change
Expand Up @@ -306,6 +306,7 @@ Known values:
Python 3.16a1 3706 (Add INTRINSIC_MATCH_CLASS_ISINSTANCE)
Python 3.16a1 3707 (GET_AWAITABLE also pushes NULL and None for SEND)
Python 3.16a1 3708 (GET_ANEXT also pushes NULL and None for SEND)
Python 3.16a1 3709 (Add pseudo instructions JUMP_IF_NONE/NOT_NONE)

Python 3.17 will start with 3750

Expand All @@ -315,7 +316,7 @@ Known values:

*/

#define PYC_MAGIC_NUMBER 3708
#define PYC_MAGIC_NUMBER 3709
/* This is equivalent to converting PYC_MAGIC_NUMBER to 2 bytes
(little-endian) and then appending b'\r\n'. */
#define PYC_MAGIC_NUMBER_TOKEN \
Expand Down
32 changes: 24 additions & 8 deletions Include/internal/pycore_opcode_metadata.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

29 changes: 15 additions & 14 deletions Include/internal/pycore_token.h

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading