Skip to content

Conversation

@MannXo
Copy link

@MannXo MannXo commented Oct 22, 2025

What do these changes do?

Adapt async context managers to behave like single-yield async iterators.

1- Allow app.cleanup_ctx callbacks to return either:
a single-yield async generator (existing behavior), or
an async context manager (e.g. @contextlib.asynccontextmanager).

2- Internally adapt async context managers with a small adapter so:
__aenter__ runs at startup (equivalent to the generator yielding), and
__aexit__ runs at cleanup (equivalent to finishing the generator).

3- Preserve previous cleanup/error aggregation semantics.

Are there changes in behavior for the user?

No breaking changes; this is fully backwards compatible.

  • Existing async-generator cleanup contexts continue to work unchanged.
  • New: callers may pass contextlib.asynccontextmanager instances for cleanup contexts.

Is it a substantial burden for the maintainers to support this?

No

Related issue number

Closes #11681

Checklist

  • I think the code is well written
  • Unit tests for the changes exist
  • Documentation reflects the changes
  • If you provide code modification, please add yourself to CONTRIBUTORS.txt
    • The format is <Name> <Surname>.
    • Please keep alphabetical order, the file is sorted by names.
  • Add a new news fragment into the CHANGES/ folder
    • name it <issue_or_pr_num>.<type>.rst (e.g. 588.bugfix.rst)

    • if you don't have an issue number, change it to the pull request
      number after creating the PR

      • .bugfix: A bug fix for something the maintainers deemed an
        improper undesired behavior that got corrected to match
        pre-agreed expectations.
      • .feature: A new behavior, public APIs. That sort of stuff.
      • .deprecation: A declaration of future API removals and breaking
        changes in behavior.
      • .breaking: When something public is removed in a breaking way.
        Could be deprecated in an earlier release.
      • .doc: Notable updates to the documentation structure or build
        process.
      • .packaging: Notes for downstreams about unobvious side effects
        and tooling. Changes in the test invocation considerations and
        runtime assumptions.
      • .contrib: Stuff that affects the contributor experience. e.g.
        Running tests, building the docs, setting up the development
        environment.
      • .misc: Changes that are hard to assign to any of the above
        categories.
    • Make sure to use full sentences with correct case and punctuation,
      for example:

      Fixed issue with non-ascii contents in doctest text files
      -- by :user:`contributor-gh-handle`.

      Use the past tense or the present tense a non-imperative mood,
      referring to what's changed compared to the last released version
      of this project.

…\nAdapt async context managers to behave like single-yield async iterators and add tests.
@psf-chronographer psf-chronographer bot added the bot:chronographer:provided There is a change note present in this PR label Oct 22, 2025
@codspeed-hq
Copy link

codspeed-hq bot commented Oct 22, 2025

CodSpeed Performance Report

Merging #11704 will not alter performance

Comparing MannXo:feature/accept-async-context-manager-for-cleanup-context (8291fa9) with master (1569ad9)

Summary

✅ 59 untouched

@codecov
Copy link

codecov bot commented Oct 22, 2025

Codecov Report

❌ Patch coverage is 96.77419% with 3 lines in your changes missing coverage. Please review.
✅ Project coverage is 98.74%. Comparing base (1569ad9) to head (8291fa9).
✅ All tests successful. No failed tests found.

Files with missing lines Patch % Lines
aiohttp/web_app.py 88.00% 2 Missing and 1 partial ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master   #11704      +/-   ##
==========================================
- Coverage   98.74%   98.74%   -0.01%     
==========================================
  Files         127      127              
  Lines       43549    43632      +83     
  Branches     2327     2331       +4     
==========================================
+ Hits        43003    43083      +80     
- Misses        390      392       +2     
- Partials      156      157       +1     
Flag Coverage Δ
CI-GHA 98.62% <96.77%> (-0.01%) ⬇️
OS-Linux 98.36% <96.77%> (-0.01%) ⬇️
OS-Windows 96.69% <96.77%> (-0.01%) ⬇️
OS-macOS 97.58% <96.77%> (-0.01%) ⬇️
Py-3.10.11 97.15% <96.77%> (-0.01%) ⬇️
Py-3.10.18 97.65% <96.77%> (+<0.01%) ⬆️
Py-3.11.13 97.84% <96.77%> (-0.01%) ⬇️
Py-3.11.9 97.35% <96.77%> (-0.01%) ⬇️
Py-3.12.10 97.45% <96.77%> (-0.01%) ⬇️
Py-3.12.11 97.94% <96.77%> (-0.01%) ⬇️
Py-3.13.7 97.95% <96.77%> (+<0.01%) ⬆️
Py-3.13.8 97.43% <96.77%> (-0.01%) ⬇️
Py-3.14.0 98.15% <96.77%> (-0.02%) ⬇️
Py-3.14.0t 97.22% <96.77%> (-0.01%) ⬇️
Py-pypy3.10.16-7.3.19 87.22% <96.77%> (-6.27%) ⬇️
VM-macos 97.58% <96.77%> (-0.01%) ⬇️
VM-ubuntu 98.36% <96.77%> (-0.01%) ⬇️
VM-windows 96.69% <96.77%> (-0.01%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Comment on lines 454 to 456
# If the callback returned an async context manager (has
# __aenter__ and __aexit__), wrap it so it behaves like an
# async iterator that yields once.
Copy link
Member

@Dreamsorcerer Dreamsorcerer Oct 22, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it make more sense to make context managers our de facto default now? Surely then all we need to do for backwards compatibility is:

if not isinstance(ctx, AbstractAsyncContextManager):
    ctx = asynccontextmanager(ctx)

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pushed a fix making it the default.

Copy link
Member

@Dreamsorcerer Dreamsorcerer Oct 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No, I mean that the code should should be changed to use aenter/aexit instead of anext. Then we don't need the awkward _AsyncCMAsIterator class and much of the other code becomes much simpler.

@Dreamsorcerer Dreamsorcerer added the backport-3.14 Trigger automatic backporting to the 3.14 release branch by Patchback robot label Oct 22, 2025
@webknjaz webknjaz requested a review from bdraco October 22, 2025 20:55
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

backport-3.14 Trigger automatic backporting to the 3.14 release branch by Patchback robot bot:chronographer:provided There is a change note present in this PR

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Accepting async context managers for cleanup contexts

3 participants