Skip to content

Commit 4639dc3

Browse files
Use async context managers for event streams
1 parent ae059da commit 4639dc3

File tree

1 file changed

+11
-11
lines changed
  • python-packages/smithy-event-stream/smithy_event_stream/aio

1 file changed

+11
-11
lines changed

python-packages/smithy-event-stream/smithy_event_stream/aio/interfaces.py

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -19,15 +19,15 @@ async def send(self, event: E) -> None:
1919
"""
2020
...
2121

22-
def close(self) -> None:
22+
async def close(self) -> None:
2323
"""Closes the event stream."""
2424
...
2525

26-
def __enter__(self) -> Self:
26+
async def __aenter__(self) -> Self:
2727
return self
2828

29-
def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any):
30-
self.close()
29+
async def __aexit__(self, exc_type: Any, exc_value: Any, traceback: Any):
30+
await self.close()
3131

3232

3333
class OutputEventStream[E: DeserializeableShape](Protocol):
@@ -48,25 +48,25 @@ async def receive(self) -> E | None:
4848
"""
4949
...
5050

51-
def close(self) -> None:
51+
async def close(self) -> None:
5252
"""Closes the event stream."""
5353
...
5454

5555
async def __anext__(self) -> E:
5656
result = await self.receive()
5757
if result is None:
58-
self.close()
58+
await self.close()
5959
raise StopAsyncIteration
6060
return result
6161

6262
def __aiter__(self) -> Self:
6363
return self
6464

65-
def __enter__(self) -> Self:
65+
async def __enter__(self) -> Self:
6666
return self
6767

68-
def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any):
69-
self.close()
68+
async def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any):
69+
await self.close()
7070

7171

7272
class EventStream[I: InputEventStream[Any] | None, O: OutputEventStream[Any] | None, R](
@@ -85,7 +85,7 @@ async def main():
8585
8686
async with client.stream_messages(input=input) as stream:
8787
stream.input_stream.send(MessageStreamMessage("Chat logger starting up."))
88-
response_handler = handle_output(stream)
88+
response_task = asyncio.create_task(handle_output(stream))
8989
stream.input_stream.send(MessageStreamMessage("Chat logger active."))
9090
await response_handler
9191
@@ -168,7 +168,7 @@ async def close(self) -> None:
168168
_, self.output_stream = await self.await_output()
169169

170170
if self.output_stream is not None:
171-
self.output_stream.close()
171+
await self.output_stream.close()
172172

173173
async def __aenter__(self) -> Self:
174174
return self

0 commit comments

Comments
 (0)