Skip to content

Commit

Permalink
Added typing spec chapter focused on exception behavior (#1718)
Browse files Browse the repository at this point in the history
* Added typing spec chapter focused on exception behavior — in particular, context managers and whether they suppress exceptions.

* Incorporated PR feedback.

* Incorporated feedback from Guido.
  • Loading branch information
erictraut committed Apr 22, 2024
1 parent 226b528 commit 2535760
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
63 changes: 63 additions & 0 deletions docs/spec/exceptions.rst
@@ -0,0 +1,63 @@
Exceptions
==========

Some type checking behaviors, such as type narrowing and reachability analysis,
require a type checker to understand code flow. Code flow normally proceeds
from one statement to the next, but some statements such as ``for``, ``while``
and ``return`` can change the code flow. Similarly, ``try``/``except``/``finally``
statements affect code flow and therefore can affect type evaluation. For example::

x = None
try:
some_function()
x = 1
except NotImplementedError:
pass

# The type of `x` at this point could be None if `some_function` raises
# an exception or `Literal[1]` if it doesn't, so a type checker may
# choose to narrow its type based on this analysis.
reveal_type(x) # Literal[1] | None


Context Managers
----------------

A context manager may optionally "suppress" exceptions by returning ``True``
(or some other truthy value) from its ``__exit__`` method. When such a context
manager is used, any exceptions that are raised and otherwise uncaught within
the ``with`` block are caught by the context manager, and control continues
immediately after the ``with`` block. If a context manager does not suppress
exceptions (as is typically the case), any exceptions that are raised and
otherwise uncaught within the ``with`` block propagate beyond the ``with``
block.

Type checkers that employ code flow analysis must be able to distinguish
between these two cases. This is done by examining the return type
annotation of the ``__exit__`` method of the context manager.

If the return type of the ``__exit__`` method is specifically ``bool`` or
``Literal[True]``, a type checker should assume that exceptions *can be*
suppressed. For any other return type, a type checker should assume that
exceptions *are not* suppressed. Examples include: ``Any``, ``Literal[False]``,
``None``, and ``bool | None``.

This convention was chosen because most context managers do not suppress
exceptions, and it is common for their ``__exit__`` method to be annotated as
returning ``bool | None``. Context managers that suppress exceptions are
relatively rare, so they are considered a special case.

For example, the following context manager suppresses exceptions::

class Suppress:
def __enter__(self) -> None:
pass

def __exit__(self, exc_type, exc_value, traceback) -> bool:
return True

with Suppress():
raise ValueError("This exception is suppressed")

# The exception is suppressed, so this line is reachable.
print("Code is reachable")
1 change: 1 addition & 0 deletions docs/spec/index.rst
Expand Up @@ -19,6 +19,7 @@ Specification for the Python type system
callables
constructors
overload
exceptions
dataclasses
typeddict
tuples
Expand Down

0 comments on commit 2535760

Please sign in to comment.