python Python PEPs ·

PEP 824 Proposes None-Coalescing Operators `??` and `??=` for Python 3.16

engineer
announcement feature

A new Python Enhancement Proposal (PEP 824) outlines the addition of two None-coalescing operators, `??` and `??=`, to the language. These operators aim to simplify common patterns for handling `None` values, offering a more concise and predictable way to provide fallback values or conditionally assign them. Proposed as a draft for Python 3.16, the operators reduce boilerplate code and mitigate issues like unintended side effects from repeated expressions when checking for `None`. This initiative addresses long-standing community discussions for a dedicated null-coalescing mechanism, similar to those found in other modern languages.

  • Introduce the Python None-coalescing `??` operator
  • Introduce the Python None-coalescing assignment `??=` operator
  • Simplify `None` handling and improve code readability
Features (2)
  • Introduce the Python None-coalescing `??` operator

    The proposed `??` operator evaluates its left-hand side expression. If the result is not `None`, that result is returned; otherwise, the right-hand side is evaluated and returned. This provides a compact syntax for handling `None` values, similar to null-coalescing operators in other languages.

  • Introduce the Python None-coalescing assignment `??=` operator

    The `??=` operator performs a conditional assignment, evaluating the left-hand side first. If the left-hand side evaluates to `None`, the right-hand side is then evaluated and assigned to the left-hand side, streamlining in-place default assignments.

Notes (1)
  • Simplify `None` handling and improve code readability

    These new operators address the verbosity and potential pitfalls of explicit `is None` checks and `if-else` expressions for default value assignment. They aim to reduce code duplication, prevent double evaluation of expressions with side effects, and offer a more consistent and readable way for Python developers to manage `None`.

Read the original announcement →

https://peps.python.org/pep-0824/

Related releases