Skip to content

Commit 3a57764

Browse files
committed
gh-115177: Mention PYTHONOPTIMIZE in assert statement docs and add warning
Add a cross-reference to the PYTHONOPTIMIZE environment variable alongside the existing -O flag mention, and add a warning advising against using assert for production data validation or interface enforcement.
1 parent 29a920e commit 3a57764

1 file changed

Lines changed: 12 additions & 5 deletions

File tree

Doc/reference/simple_stmts.rst

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -404,11 +404,18 @@ The extended form, ``assert expression1, expression2``, is equivalent to ::
404404
These equivalences assume that :const:`__debug__` and :exc:`AssertionError` refer to
405405
the built-in variables with those names. In the current implementation, the
406406
built-in variable ``__debug__`` is ``True`` under normal circumstances,
407-
``False`` when optimization is requested (command line option :option:`-O`). The current
408-
code generator emits no code for an :keyword:`assert` statement when optimization is
409-
requested at compile time. Note that it is unnecessary to include the source
410-
code for the expression that failed in the error message; it will be displayed
411-
as part of the stack trace.
407+
``False`` when optimization is requested (command line option :option:`-O` or the
408+
:envvar:`PYTHONOPTIMIZE` environment variable). The current code generator emits
409+
no code for an :keyword:`assert` statement when optimization is requested at
410+
compile time. Note that it is unnecessary to include the source code for the
411+
expression that failed in the error message; it will be displayed as part of the
412+
stack trace.
413+
414+
.. warning::
415+
416+
Since :keyword:`assert` statements are removed when optimization is enabled,
417+
do not use them to enforce interface constraints or validate data in
418+
production code — use :keyword:`if` statements and raise exceptions instead.
412419

413420
Assignments to :const:`__debug__` are illegal. The value for the built-in variable
414421
is determined when the interpreter starts.

0 commit comments

Comments
 (0)