Skip to content

Add subdiagnostic hint if async context manager is used in non-async with statement #508

@AlexWaygood

Description

@AlexWaygood

CPython just added a really nice hint to its diagnostic message if you use an async context manager in a non-async with statement:

Python 3.14.0a7+ (heads/main:fac41f56d4b, May 25 2025, 12:27:36) [Clang 17.0.0 (clang-1700.0.13.3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> class Foo:
...     async def __aenter__(self): ...
...     async def __aexit__(self, *args): ...
...     
>>> with Foo():
...     ...
...     
Traceback (most recent call last):
  File "<python-input-1>", line 1, in <module>
    with Foo():
         ~~~^^
TypeError: 'Foo' object does not support the context manager protocol (missed __exit__ method) but it supports the asynchronous context manager protocol. Did you mean to use 'async with'?

We should add a subdiagnostic to our equivalent error message that suggests using async with instead of with, so that it looks something like:

error: Object of type `Foo` cannot be used with `with` because it does not implement `__enter__` and `__exit__`
note: Objects of type `Foo` *can* be used as async context managers
note: Consider using `async with` here

(Here's a playground link to show our current error message: https://play.ty.dev/00fecd74-416e-46d1-8368-a2b87cbb84cd.)

Metadata

Metadata

Assignees

No one assigned

    Labels

    diagnosticsRelated to reporting of diagnostics.help wantedContributions especially welcome

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions