@@ -780,6 +780,96 @@ asyncio
780
780
It now raises a :exc: `RuntimeError ` if there is no current event loop.
781
781
(Contributed by Kumar Aditya in :gh: `126353 `.)
782
782
783
+ There's a few patterns that use :func: `asyncio.get_event_loop `, most
784
+ of them can be replaced with :func: `asyncio.run `.
785
+
786
+ If you're running an async function, simply use :func: `asyncio.run `.
787
+
788
+ Before::
789
+
790
+ async def main():
791
+ ...
792
+
793
+
794
+ loop = asyncio.get_event_loop()
795
+ try:
796
+ loop.run_until_complete(main())
797
+ finally:
798
+ loop.close()
799
+
800
+ After::
801
+
802
+ async def main():
803
+ ...
804
+
805
+ asyncio.run(main())
806
+
807
+ If you need to start something, e.g. a server listening on a socket
808
+ and then run forever, use :func: `asyncio.run ` and an
809
+ :class: `asyncio.Event `.
810
+
811
+ Before::
812
+
813
+ def start_server(loop):
814
+ ...
815
+
816
+ loop = asyncio.get_event_loop()
817
+ try:
818
+ start_server(loop)
819
+ loop.run_forever()
820
+ finally:
821
+ loop.close()
822
+
823
+ After::
824
+
825
+ def start_server(loop):
826
+ ...
827
+
828
+ async def main():
829
+ start_server(asyncio.get_running_loop())
830
+ await asyncio.Event().wait()
831
+
832
+ asyncio.run(main())
833
+
834
+ If you need to run something in an event loop, then run some blocking
835
+ code around it, use :class: `asyncio.Runner `.
836
+
837
+ Before::
838
+
839
+ async def operation_one():
840
+ ...
841
+
842
+ def blocking_code():
843
+ ...
844
+
845
+ async def operation_two():
846
+ ...
847
+
848
+ loop = asyncio.get_event_loop()
849
+ try:
850
+ loop.run_until_complete(operation_one())
851
+ blocking_code()
852
+ loop.run_until_complete(operation_two())
853
+ finally:
854
+ loop.close()
855
+
856
+ After::
857
+
858
+ async def operation_one():
859
+ ...
860
+
861
+ def blocking_code():
862
+ ...
863
+
864
+ async def operation_two():
865
+ ...
866
+
867
+ with asyncio.Runner() as runner:
868
+ runner.run(operation_one())
869
+ blocking_code()
870
+ runner.run(operation_two())
871
+
872
+
783
873
784
874
collections.abc
785
875
---------------
0 commit comments