Skip to content

Commit c9d61b7

Browse files
committed
Merge branch 'cleanup-auto-aiter' into aclose-fixed-omnibus
2 parents 8ed364c + 22cffd0 commit c9d61b7

File tree

3 files changed

+27
-7
lines changed

3 files changed

+27
-7
lines changed

CHANGES.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ Unreleased
88
- Use modern packaging metadata with ``pyproject.toml`` instead of ``setup.cfg``.
99
:pr:`1793`
1010
- Use ``flit_core`` instead of ``setuptools`` as build backend.
11+
- Avoid unclosed ``auto_aiter`` warnings. :pr:`1954`
1112

1213

1314
Version 3.1.3

src/jinja2/async_utils.py

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66
from .utils import _PassArg
77
from .utils import pass_eval_context
88

9+
if t.TYPE_CHECKING:
10+
import typing_extensions as te
11+
912
V = t.TypeVar("V")
1013

1114

@@ -67,15 +70,27 @@ async def auto_await(value: t.Union[t.Awaitable["V"], "V"]) -> "V":
6770
return t.cast("V", value)
6871

6972

70-
async def auto_aiter(
73+
class _IteratorToAsyncIterator(t.Generic[V]):
74+
def __init__(self, iterator: "t.Iterator[V]"):
75+
self._iterator = iterator
76+
77+
def __aiter__(self) -> "te.Self":
78+
return self
79+
80+
async def __anext__(self) -> V:
81+
try:
82+
return next(self._iterator)
83+
except StopIteration as e:
84+
raise StopAsyncIteration(e.value) from e
85+
86+
87+
def auto_aiter(
7188
iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
7289
) -> "t.AsyncIterator[V]":
7390
if hasattr(iterable, "__aiter__"):
74-
async for item in t.cast("t.AsyncIterable[V]", iterable):
75-
yield item
91+
return iterable.__aiter__()
7692
else:
77-
for item in iterable:
78-
yield item
93+
return _IteratorToAsyncIterator(iter(iterable))
7994

8095

8196
async def auto_to_list(

src/jinja2/compiler.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -973,14 +973,18 @@ def visit_Block(self, node: nodes.Block, frame: Frame) -> None:
973973
f"yield from context.blocks[{node.name!r}][0]({context})", node
974974
)
975975
else:
976+
self.writeline("gen = context.blocks[{node.name!r}][0]({context})")
977+
self.writeline("try:")
978+
self.indent()
976979
self.writeline(
977-
f"{self.choose_async()}for event in"
978-
f" context.blocks[{node.name!r}][0]({context}):",
980+
f"{self.choose_async()}for event in gen:"
979981
node,
980982
)
981983
self.indent()
982984
self.simple_write("event", frame)
983985
self.outdent()
986+
self.outdent()
987+
self.write_line(f"finally: {self.choose_async('await gen.aclose()', 'gen.close()')}")
984988

985989
self.outdent(level)
986990

0 commit comments

Comments
 (0)