Skip to content

Commit

Permalink
Improved the docs regarding exception groups
Browse files Browse the repository at this point in the history
  • Loading branch information
agronholm committed Jan 30, 2022
1 parent e2fbec0 commit 16e33b1
Show file tree
Hide file tree
Showing 4 changed files with 88 additions and 44 deletions.
76 changes: 41 additions & 35 deletions docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,17 +19,20 @@
#
import os
import sys

# For our local_customization module
sys.path.insert(0, os.path.abspath('.'))
sys.path.insert(0, os.path.abspath("."))
# For trio itself
sys.path.insert(0, os.path.abspath('../..'))
sys.path.insert(0, os.path.abspath("../.."))

# https://docs.readthedocs.io/en/stable/builds.html#build-environment
if "READTHEDOCS" in os.environ:
import glob

if glob.glob("../../newsfragments/*.*.rst"):
print("-- Found newsfragments; running towncrier --", flush=True)
import subprocess

subprocess.run(
["towncrier", "--yes", "--date", "not released yet"],
cwd="../..",
Expand Down Expand Up @@ -66,6 +69,7 @@
def setup(app):
app.add_css_file("hackrtd.css")


# -- General configuration ------------------------------------------------

# If your documentation needs a minimal Sphinx version, state it here.
Expand All @@ -76,44 +80,46 @@ def setup(app):
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.intersphinx',
'sphinx.ext.coverage',
'sphinx.ext.napoleon',
'sphinxcontrib_trio',
'local_customization',
"sphinx.ext.autodoc",
"sphinx.ext.intersphinx",
"sphinx.ext.coverage",
"sphinx.ext.napoleon",
"sphinxcontrib_trio",
"local_customization",
]

# FIXME: change the "python" link back to /3 when Python 3.11 is released
intersphinx_mapping = {
"python": ('https://docs.python.org/3', None),
"outcome": ('https://outcome.readthedocs.io/en/latest/', None),
"python": ("https://docs.python.org/3.11", None),
"outcome": ("https://outcome.readthedocs.io/en/latest/", None),
}

autodoc_member_order = "bysource"

# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
templates_path = ["_templates"]

# The suffix(es) of source filenames.
# You can specify multiple suffix as a list of string:
#
# source_suffix = ['.rst', '.md']
source_suffix = '.rst'
source_suffix = ".rst"

# The master toctree document.
master_doc = 'index'
master_doc = "index"

# General information about the project.
project = 'Trio'
copyright = '2017, Nathaniel J. Smith'
author = 'Nathaniel J. Smith'
project = "Trio"
copyright = "2017, Nathaniel J. Smith"
author = "Nathaniel J. Smith"

# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
import trio

version = trio.__version__
# The full version, including alpha/beta/rc tags.
release = version
Expand All @@ -135,9 +141,9 @@ def setup(app):
exclude_patterns = []

# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'default'
pygments_style = "default"

highlight_language = 'python3'
highlight_language = "python3"

# If true, `todo` and `todoList` produce output, else they produce nothing.
todo_include_todos = False
Expand All @@ -152,13 +158,14 @@ def setup(app):
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
#html_theme = 'alabaster'
# html_theme = 'alabaster'

# We have to set this ourselves, not only because it's useful for local
# testing, but also because if we don't then RTD will throw away our
# html_theme_options.
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'

html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]

# Theme options are theme-specific and customize the look and feel of a theme
Expand All @@ -173,19 +180,19 @@ def setup(app):
# versions/settings...
"navigation_depth": 4,
"logo_only": True,
'prev_next_buttons_location': 'both'
"prev_next_buttons_location": "both",
}

# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['_static']
html_static_path = ["_static"]


# -- Options for HTMLHelp output ------------------------------------------

# Output file base name for HTML help builder.
htmlhelp_basename = 'Triodoc'
htmlhelp_basename = "Triodoc"


# -- Options for LaTeX output ---------------------------------------------
Expand All @@ -194,15 +201,12 @@ def setup(app):
# The paper size ('letterpaper' or 'a4paper').
#
# 'papersize': 'letterpaper',

# The font size ('10pt', '11pt' or '12pt').
#
# 'pointsize': '10pt',

# Additional stuff for the LaTeX preamble.
#
# 'preamble': '',

# Latex figure (float) alignment
#
# 'figure_align': 'htbp',
Expand All @@ -212,19 +216,15 @@ def setup(app):
# (source start file, target name, title,
# author, documentclass [howto, manual, or own class]).
latex_documents = [
(master_doc, 'Trio.tex', 'Trio Documentation',
'Nathaniel J. Smith', 'manual'),
(master_doc, "Trio.tex", "Trio Documentation", "Nathaniel J. Smith", "manual"),
]


# -- Options for manual page output ---------------------------------------

# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
(master_doc, 'trio', 'Trio Documentation',
[author], 1)
]
man_pages = [(master_doc, "trio", "Trio Documentation", [author], 1)]


# -- Options for Texinfo output -------------------------------------------
Expand All @@ -233,7 +233,13 @@ def setup(app):
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
(master_doc, 'Trio', 'Trio Documentation',
author, 'Trio', 'One line description of project.',
'Miscellaneous'),
(
master_doc,
"Trio",
"Trio Documentation",
author,
"Trio",
"One line description of project.",
"Miscellaneous",
),
]
45 changes: 40 additions & 5 deletions docs/source/reference-core.rst
Original file line number Diff line number Diff line change
Expand Up @@ -687,6 +687,8 @@ You might wonder why Trio can't just remember "this task should be cancelled in

If you want a timeout to apply to one task but not another, then you need to put the cancel scope in that individual task's function -- ``child()``, in this example.

.. _exceptiongroups:

Errors in multiple child tasks
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Expand All @@ -709,13 +711,46 @@ limitation. Consider code like::

``broken1`` raises ``KeyError``. ``broken2`` raises
``IndexError``. Obviously ``parent`` should raise some error, but
what? In some sense, the answer should be "both of these at once", but
in Python there can only be one exception at a time.
what? The answer is that both exceptions are grouped in an `ExceptionGroup`.
The `ExceptionGroup` and its parent class `BaseExceptionGroup` are used to encapsulate
multiple exceptions being raised at once.

To catch individual exceptions encapsulated in an exception group, the ``except*``
clause was introduced in Python 3.11 (:pep:`654`). Here's how it works::

try:
async with trio.open_nursery() as nursery:
nursery.start_soon(broken1)
nursery.start_soon(broken2)
except* KeyError:
... # handle each KeyError
except* IndexError:
... # handle each IndexError

But what if you can't use ``except*`` just yet? Well, for that there is the handy
exceptiongroup_ library which lets you approximate this behavior with exception handler
callbacks::

from exceptiongroup import catch

def handle_keyerror(exc):
... # handle each KeyError

def handle_indexerror(exc):
... # handle each IndexError

with catch({
KeyError: handle_keyerror,
IndexError: handle_indexerror
}):
async with trio.open_nursery() as nursery:
nursery.start_soon(broken1)
nursery.start_soon(broken2)

Trio's answer is that it raises a ``BaseExceptionGroup`` object. This is a
special exception which encapsulates multiple exception objects –
either regular exceptions or nested ``BaseExceptionGroup``\s.
.. hint:: If your code, written using ``except*``, would set local variables, you can do
the same with handler callbacks as long as you declare those variables ``nonlocal``.

.. _exceptiongroup: https://pypi.org/project/exceptiongroup/

Spawning tasks without becoming a parent
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Expand Down
7 changes: 7 additions & 0 deletions newsfragments/2211.breaking.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
``trio.MultiError`` has been removed in favor of the built-in :exc:`BaseExceptionGroup`
(and its derivative :exc:`ExceptionGroup`), falling back to the backport_ on
Python < 3.11.
See the :ref:`updated documentation <exceptiongroups>` on how to deal with exception
groups.

.. _backport: https://pypi.org/project/exceptiongroup/
4 changes: 0 additions & 4 deletions newsfragments/2211.removal.rst

This file was deleted.

0 comments on commit 16e33b1

Please sign in to comment.