google / google/styleguide

Python styleguide `ExceptionGroup` update for docstrings

Open
#907 5 comments 2 reactions 1 assignee Claimed by @nathanielmanistaatgoogle View on GitHub
lang:python
Dominant language
HTML
Stars
39.6k
Forks
12.9k
Avg merge
42m
Merged PRs (30d)
15

Description

[PEP 654](https://peps.python.org/pep-0654/) introduced exception groups: "a combination of multiple unrelated exceptions". This changes how exceptions are handled by the user:

```py
def some_method():
ex1 = ValueError("value_error")
ex2 = TypeError("type_error")

raise ExceptionGroup("exception_group", [ex1, ex2])

try:
some_method()
except (ValueError, TypeError):
print("This will not run")
except Exception:
print("This will run")

try:
some_method()
except ExceptionGroup:
print("This will run")

try:
some_method()
except* (ValueError, TypeError):
print("This will run")
```

Making it important to warn users that they should either catch `ExceptionGroup` or use `except*`.

The [relevant styleguide section](https://google.github.io/styleguide/pyguide.html#doc-function-raises) doesn't yet mention exception groups. What would be the correct way to document this?

The docstring below may lead users to not catch `ExceptionGroup` or use `except*`, causing their code to break.
```py
def some_method():
"""
My method.

Raises:
ValueError: Some value error.
TypeError: Some type error.
"""
```

The docstring below doesn't make sense for two main reasons:
1. The PEP itself describes an exception group as "a combination of multiple unrelated exceptions". How would one describe an exception group that doesn't throw anything in particular?
2. The user may want to catch different exception types raised by the exception groups to handle them separately. To do so they would need to open the method itself, defeating the purpose of documenting the exception type.

```py
def some_method():
"""
My method.

Raises:
ExceptionGroup: ???
"""
```

I think we may need entirely new guidelines for exception groups. Maybe something like:
```py
def some_method():
"""
My method.

Raises:
ExceptionGroup:
ValueError: Some value error.
TypeError: Some type error.
"""
```

or

```py
def some_method():
"""
My method.

Raises:
*ValueError: Some value error.
*TypeError: Some type error.
"""
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.