Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
bd00fcb
gh-125862: Improve context decorator support for generators and async…
agronholm Jul 2, 2025
1a0c100
Merge branch 'main' into fix-issue-125862
agronholm Jul 2, 2025
9b3ba13
📜🤖 Added by blurb_it.
blurb-it[bot] Jul 2, 2025
8535a21
Manually iterate coroutines to avoid asyncio use
agronholm Jul 2, 2025
6a68ffb
Merge branch 'main' into fix-issue-125862
agronholm Jul 2, 2025
bbaee0c
Merge branch 'main' into fix-issue-125862
agronholm Dec 8, 2025
93b30f4
Merge branch 'main' into fix-issue-125862
agronholm Dec 9, 2025
1fd52d5
Make sure we at least try to close the generators
agronholm Dec 9, 2025
e32191e
Merge remote-tracking branch 'fork/fix-issue-125862' into fix-issue-1…
agronholm Dec 9, 2025
65c8f50
Use (a)closing
agronholm Dec 9, 2025
8762048
Merge branch 'main' into fix-issue-125862
agronholm Dec 15, 2025
6fb5bcb
Merge remote-tracking branch 'origin/main' into fix-issue-125862
gpshead Apr 27, 2026
1433534
Use _private imports
gpshead Apr 27, 2026
a8ee60d
performance: only define inner funcs on the branch that uses them, la…
gpshead Apr 27, 2026
46ffa37
do not delete that newline (small diff)
gpshead Apr 27, 2026
ed6d9fa
reword reST news entry
gpshead Apr 27, 2026
876704a
Preserve generator return value; expand decorator test coverage
gpshead Apr 27, 2026
3b30193
Document ContextDecorator generator/coroutine handling
gpshead Apr 27, 2026
72d4a8e
Add What's New entry for ContextDecorator generator support
gpshead Apr 27, 2026
719c55c
simplify lazy import syntax
gpshead Apr 27, 2026
59422a3
Reword AsyncContextDecorator docs to lead with intended async use
gpshead Apr 28, 2026
7026b14
Reword test comments to state the contract, not the mechanism
gpshead Apr 28, 2026
c6eda4a
Test send/throw forwarding for the sync wrapper; pin async limitation
gpshead Apr 28, 2026
a3cfb1a
also add my name in whatsnew
gpshead Apr 28, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 50 additions & 4 deletions Lib/contextlib.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
"""Utilities for with-statement contexts. See PEP 343."""
from inspect import isasyncgenfunction, iscoroutinefunction, \
isgeneratorfunction

import abc
import os
import sys
Expand Down Expand Up @@ -79,11 +82,32 @@ def _recreate_cm(self):
return self

def __call__(self, func):
@wraps(func)
def inner(*args, **kwds):
with self._recreate_cm():
return func(*args, **kwds)
return inner

def gen_inner(*args, **kwds):
with self._recreate_cm():
yield from func(*args, **kwds)
Comment thread
gpshead marked this conversation as resolved.
Outdated

async def async_inner(*args, **kwds):
with self._recreate_cm():
return await func(*args, **kwds)

async def asyncgen_inner(*args, **kwds):
with self._recreate_cm():
async for value in func(*args, **kwds):
yield value

wrapper = wraps(func)
if isasyncgenfunction(func):
return wrapper(asyncgen_inner)
elif iscoroutinefunction(func):
return wrapper(async_inner)
elif isgeneratorfunction(func):
return wrapper(gen_inner)
else:
return wrapper(inner)


class AsyncContextDecorator(object):
Expand All @@ -95,11 +119,33 @@ def _recreate_cm(self):
return self

def __call__(self, func):
@wraps(func)
async def inner(*args, **kwds):
async with self._recreate_cm():
return func(*args, **kwds)

async def gen_inner(*args, **kwds):
async with self._recreate_cm():
for value in func(*args, **kwds):
yield value

async def async_inner(*args, **kwds):
async with self._recreate_cm():
return await func(*args, **kwds)
return inner

async def asyncgen_inner(*args, **kwds):
async with self._recreate_cm():
async for value in func(*args, **kwds):
yield value

wrapper = wraps(func)
if isasyncgenfunction(func):
return wrapper(asyncgen_inner)
elif iscoroutinefunction(func):
return wrapper(async_inner)
elif isgeneratorfunction(func):
return wrapper(gen_inner)
else:
return wrapper(inner)


class _GeneratorContextManagerBase:
Expand Down
69 changes: 68 additions & 1 deletion Lib/test/test_contextlib.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""Unit tests for contextlib.py, and other context managers."""

import io
import os
import sys
Expand Down Expand Up @@ -680,6 +679,74 @@ def test(x):
self.assertEqual(state, [1, 'something else', 999])


def test_contextmanager_decorate_generator_function(self):
@contextmanager
def woohoo(y):
state.append(y)
yield
state.append(999)

state = []
@woohoo(1)
def test(x):
self.assertEqual(state, [1])
state.append(x)
yield
state.append("second item")

for _ in test("something"):
self.assertEqual(state, [1, "something"])
self.assertEqual(state, [1, "something", "second item", 999])


def test_contextmanager_decorate_coroutine_function(self):
@contextmanager
def woohoo(y):
state.append(y)
yield
state.append(999)

state = []
@woohoo(1)
async def test(x):
self.assertEqual(state, [1])
state.append(x)

coro = test('something')
with self.assertRaises(StopIteration):
coro.send(None)

self.assertEqual(state, [1, 'something', 999])


def test_contextmanager_decorate_asyncgen_function(self):
@contextmanager
def woohoo(y):
state.append(y)
yield
state.append(999)

state = []
@woohoo(1)
async def test(x):
self.assertEqual(state, [1])
state.append(x)
yield
state.append("second item")

async def run_test():
async for _ in test("something"):
self.assertEqual(state, [1, "something"])

agen = test('something')
with self.assertRaises(StopIteration):
agen.asend(None).send(None)
with self.assertRaises(StopAsyncIteration):
agen.asend(None).send(None)

self.assertEqual(state, [1, 'something', "second item", 999])


class TestBaseExitStack:
exit_stack = None

Expand Down
57 changes: 57 additions & 0 deletions Lib/test/test_contextlib_async.py
Original file line number Diff line number Diff line change
Expand Up @@ -402,6 +402,63 @@ async def test():
await test()
self.assertFalse(entered)

@_async_test
async def test_decorator_decorate_sync_function(self):
@asynccontextmanager
async def context():
state.append(1)
yield
state.append(999)

state = []
@context()
def test(x):
self.assertEqual(state, [1])
state.append(x)

await test("something")
self.assertEqual(state, [1, "something", 999])

@_async_test
async def test_decorator_decorate_generator_function(self):
@asynccontextmanager
async def context():
state.append(1)
yield
state.append(999)

state = []
@context()
def test(x):
self.assertEqual(state, [1])
state.append(x)
yield
state.append("second item")

async for _ in test("something"):
self.assertEqual(state, [1, "something"])
self.assertEqual(state, [1, "something", "second item", 999])

@_async_test
async def test_decorator_decorate_asyncgen_function(self):
@asynccontextmanager
async def context():
state.append(1)
yield
state.append(999)

state = []
@context()
async def test(x):
self.assertEqual(state, [1])
state.append(x)
yield
state.append("second item")

async for _ in test("something"):
self.assertEqual(state, [1, "something"])
self.assertEqual(state, [1, "something", "second item", 999])

@_async_test
async def test_decorator_with_exception(self):
entered = False
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Improved ``@contextmanager`` and ``@asynccontextmanager`` to work correctly with generators, coroutine functions and async generators when the wrapped callables are used as decorators
Loading