GH-99388: add `loop_factory` parameter to `asyncio.run` by kumaraditya303 · Pull Request #99462 · python/cpython · GitHub
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
14 changes: 10 additions & 4 deletions Doc/library/asyncio-runner.rst
5 changes: 5 additions & 0 deletions Doc/whatsnew/3.12.rst
Original file line number Diff line number Diff line change
Expand Up @@ -217,6 +217,11 @@ asyncio
and will be removed in Python 3.14.
(Contributed by Kumar Aditya in :gh:`94597`.)

* Add *loop_factory* parameter to :func:`asyncio.run` to allow specifying
a custom event loop factory.
(Contributed by Kumar Aditya in :gh:`99388`.)


pathlib
-------

Expand Down
4 changes: 2 additions & 2 deletions Lib/asyncio/runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ def _on_sigint(self, signum, frame, main_task):
raise KeyboardInterrupt()


def run(main, *, debug=None):
def run(main, *, debug=None, loop_factory=None):
"""Execute the coroutine and return the result.

This function runs the passed coroutine, taking care of
Expand Down Expand Up @@ -190,7 +190,7 @@ async def main():
raise RuntimeError(
"asyncio.run() cannot be called from a running event loop")

with Runner(debug=debug) as runner:
with Runner(debug=debug, loop_factory=loop_factory) as runner:
return runner.run(main)


Expand Down
10 changes: 10 additions & 0 deletions Lib/test/test_asyncio/test_runners.py
Original file line number Diff line number Diff line change
Expand Up @@ -257,6 +257,16 @@ def new_event_loop():
with self.assertRaises(asyncio.CancelledError):
asyncio.run(main())

def test_asyncio_run_loop_factory(self):
factory = mock.Mock()
loop = factory.return_value = self.new_loop()

async def main():
self.assertEqual(asyncio.get_running_loop(), loop)

asyncio.run(main(), loop_factory=factory)
factory.assert_called_once_with()


class RunnerTests(BaseTest):

Expand Down