events.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842
  1. """Event loop and event loop policy."""
  2. __all__ = (
  3. 'AbstractEventLoopPolicy',
  4. 'AbstractEventLoop', 'AbstractServer',
  5. 'Handle', 'TimerHandle',
  6. 'get_event_loop_policy', 'set_event_loop_policy',
  7. 'get_event_loop', 'set_event_loop', 'new_event_loop',
  8. 'get_child_watcher', 'set_child_watcher',
  9. '_set_running_loop', 'get_running_loop',
  10. '_get_running_loop',
  11. )
  12. import contextvars
  13. import os
  14. import socket
  15. import subprocess
  16. import sys
  17. import threading
  18. from . import format_helpers
  19. class Handle:
  20. """Object returned by callback registration methods."""
  21. __slots__ = ('_callback', '_args', '_cancelled', '_loop',
  22. '_source_traceback', '_repr', '__weakref__',
  23. '_context')
  24. def __init__(self, callback, args, loop, context=None):
  25. if context is None:
  26. context = contextvars.copy_context()
  27. self._context = context
  28. self._loop = loop
  29. self._callback = callback
  30. self._args = args
  31. self._cancelled = False
  32. self._repr = None
  33. if self._loop.get_debug():
  34. self._source_traceback = format_helpers.extract_stack(
  35. sys._getframe(1))
  36. else:
  37. self._source_traceback = None
  38. def _repr_info(self):
  39. info = [self.__class__.__name__]
  40. if self._cancelled:
  41. info.append('cancelled')
  42. if self._callback is not None:
  43. info.append(format_helpers._format_callback_source(
  44. self._callback, self._args))
  45. if self._source_traceback:
  46. frame = self._source_traceback[-1]
  47. info.append(f'created at {frame[0]}:{frame[1]}')
  48. return info
  49. def __repr__(self):
  50. if self._repr is not None:
  51. return self._repr
  52. info = self._repr_info()
  53. return '<{}>'.format(' '.join(info))
  54. def cancel(self):
  55. if not self._cancelled:
  56. self._cancelled = True
  57. if self._loop.get_debug():
  58. # Keep a representation in debug mode to keep callback and
  59. # parameters. For example, to log the warning
  60. # "Executing <Handle...> took 2.5 second"
  61. self._repr = repr(self)
  62. self._callback = None
  63. self._args = None
  64. def cancelled(self):
  65. return self._cancelled
  66. def _run(self):
  67. try:
  68. self._context.run(self._callback, *self._args)
  69. except (SystemExit, KeyboardInterrupt):
  70. raise
  71. except BaseException as exc:
  72. cb = format_helpers._format_callback_source(
  73. self._callback, self._args)
  74. msg = f'Exception in callback {cb}'
  75. context = {
  76. 'message': msg,
  77. 'exception': exc,
  78. 'handle': self,
  79. }
  80. if self._source_traceback:
  81. context['source_traceback'] = self._source_traceback
  82. self._loop.call_exception_handler(context)
  83. self = None # Needed to break cycles when an exception occurs.
  84. class TimerHandle(Handle):
  85. """Object returned by timed callback registration methods."""
  86. __slots__ = ['_scheduled', '_when']
  87. def __init__(self, when, callback, args, loop, context=None):
  88. super().__init__(callback, args, loop, context)
  89. if self._source_traceback:
  90. del self._source_traceback[-1]
  91. self._when = when
  92. self._scheduled = False
  93. def _repr_info(self):
  94. info = super()._repr_info()
  95. pos = 2 if self._cancelled else 1
  96. info.insert(pos, f'when={self._when}')
  97. return info
  98. def __hash__(self):
  99. return hash(self._when)
  100. def __lt__(self, other):
  101. if isinstance(other, TimerHandle):
  102. return self._when < other._when
  103. return NotImplemented
  104. def __le__(self, other):
  105. if isinstance(other, TimerHandle):
  106. return self._when < other._when or self.__eq__(other)
  107. return NotImplemented
  108. def __gt__(self, other):
  109. if isinstance(other, TimerHandle):
  110. return self._when > other._when
  111. return NotImplemented
  112. def __ge__(self, other):
  113. if isinstance(other, TimerHandle):
  114. return self._when > other._when or self.__eq__(other)
  115. return NotImplemented
  116. def __eq__(self, other):
  117. if isinstance(other, TimerHandle):
  118. return (self._when == other._when and
  119. self._callback == other._callback and
  120. self._args == other._args and
  121. self._cancelled == other._cancelled)
  122. return NotImplemented
  123. def cancel(self):
  124. if not self._cancelled:
  125. self._loop._timer_handle_cancelled(self)
  126. super().cancel()
  127. def when(self):
  128. """Return a scheduled callback time.
  129. The time is an absolute timestamp, using the same time
  130. reference as loop.time().
  131. """
  132. return self._when
  133. class AbstractServer:
  134. """Abstract server returned by create_server()."""
  135. def close(self):
  136. """Stop serving. This leaves existing connections open."""
  137. raise NotImplementedError
  138. def get_loop(self):
  139. """Get the event loop the Server object is attached to."""
  140. raise NotImplementedError
  141. def is_serving(self):
  142. """Return True if the server is accepting connections."""
  143. raise NotImplementedError
  144. async def start_serving(self):
  145. """Start accepting connections.
  146. This method is idempotent, so it can be called when
  147. the server is already being serving.
  148. """
  149. raise NotImplementedError
  150. async def serve_forever(self):
  151. """Start accepting connections until the coroutine is cancelled.
  152. The server is closed when the coroutine is cancelled.
  153. """
  154. raise NotImplementedError
  155. async def wait_closed(self):
  156. """Coroutine to wait until service is closed."""
  157. raise NotImplementedError
  158. async def __aenter__(self):
  159. return self
  160. async def __aexit__(self, *exc):
  161. self.close()
  162. await self.wait_closed()
  163. class AbstractEventLoop:
  164. """Abstract event loop."""
  165. # Running and stopping the event loop.
  166. def run_forever(self):
  167. """Run the event loop until stop() is called."""
  168. raise NotImplementedError
  169. def run_until_complete(self, future):
  170. """Run the event loop until a Future is done.
  171. Return the Future's result, or raise its exception.
  172. """
  173. raise NotImplementedError
  174. def stop(self):
  175. """Stop the event loop as soon as reasonable.
  176. Exactly how soon that is may depend on the implementation, but
  177. no more I/O callbacks should be scheduled.
  178. """
  179. raise NotImplementedError
  180. def is_running(self):
  181. """Return whether the event loop is currently running."""
  182. raise NotImplementedError
  183. def is_closed(self):
  184. """Returns True if the event loop was closed."""
  185. raise NotImplementedError
  186. def close(self):
  187. """Close the loop.
  188. The loop should not be running.
  189. This is idempotent and irreversible.
  190. No other methods should be called after this one.
  191. """
  192. raise NotImplementedError
  193. async def shutdown_asyncgens(self):
  194. """Shutdown all active asynchronous generators."""
  195. raise NotImplementedError
  196. async def shutdown_default_executor(self):
  197. """Schedule the shutdown of the default executor."""
  198. raise NotImplementedError
  199. # Methods scheduling callbacks. All these return Handles.
  200. def _timer_handle_cancelled(self, handle):
  201. """Notification that a TimerHandle has been cancelled."""
  202. raise NotImplementedError
  203. def call_soon(self, callback, *args, context=None):
  204. return self.call_later(0, callback, *args, context=context)
  205. def call_later(self, delay, callback, *args, context=None):
  206. raise NotImplementedError
  207. def call_at(self, when, callback, *args, context=None):
  208. raise NotImplementedError
  209. def time(self):
  210. raise NotImplementedError
  211. def create_future(self):
  212. raise NotImplementedError
  213. # Method scheduling a coroutine object: create a task.
  214. def create_task(self, coro, *, name=None, context=None):
  215. raise NotImplementedError
  216. # Methods for interacting with threads.
  217. def call_soon_threadsafe(self, callback, *args, context=None):
  218. raise NotImplementedError
  219. def run_in_executor(self, executor, func, *args):
  220. raise NotImplementedError
  221. def set_default_executor(self, executor):
  222. raise NotImplementedError
  223. # Network I/O methods returning Futures.
  224. async def getaddrinfo(self, host, port, *,
  225. family=0, type=0, proto=0, flags=0):
  226. raise NotImplementedError
  227. async def getnameinfo(self, sockaddr, flags=0):
  228. raise NotImplementedError
  229. async def create_connection(
  230. self, protocol_factory, host=None, port=None,
  231. *, ssl=None, family=0, proto=0,
  232. flags=0, sock=None, local_addr=None,
  233. server_hostname=None,
  234. ssl_handshake_timeout=None,
  235. ssl_shutdown_timeout=None,
  236. happy_eyeballs_delay=None, interleave=None):
  237. raise NotImplementedError
  238. async def create_server(
  239. self, protocol_factory, host=None, port=None,
  240. *, family=socket.AF_UNSPEC,
  241. flags=socket.AI_PASSIVE, sock=None, backlog=100,
  242. ssl=None, reuse_address=None, reuse_port=None,
  243. ssl_handshake_timeout=None,
  244. ssl_shutdown_timeout=None,
  245. start_serving=True):
  246. """A coroutine which creates a TCP server bound to host and port.
  247. The return value is a Server object which can be used to stop
  248. the service.
  249. If host is an empty string or None all interfaces are assumed
  250. and a list of multiple sockets will be returned (most likely
  251. one for IPv4 and another one for IPv6). The host parameter can also be
  252. a sequence (e.g. list) of hosts to bind to.
  253. family can be set to either AF_INET or AF_INET6 to force the
  254. socket to use IPv4 or IPv6. If not set it will be determined
  255. from host (defaults to AF_UNSPEC).
  256. flags is a bitmask for getaddrinfo().
  257. sock can optionally be specified in order to use a preexisting
  258. socket object.
  259. backlog is the maximum number of queued connections passed to
  260. listen() (defaults to 100).
  261. ssl can be set to an SSLContext to enable SSL over the
  262. accepted connections.
  263. reuse_address tells the kernel to reuse a local socket in
  264. TIME_WAIT state, without waiting for its natural timeout to
  265. expire. If not specified will automatically be set to True on
  266. UNIX.
  267. reuse_port tells the kernel to allow this endpoint to be bound to
  268. the same port as other existing endpoints are bound to, so long as
  269. they all set this flag when being created. This option is not
  270. supported on Windows.
  271. ssl_handshake_timeout is the time in seconds that an SSL server
  272. will wait for completion of the SSL handshake before aborting the
  273. connection. Default is 60s.
  274. ssl_shutdown_timeout is the time in seconds that an SSL server
  275. will wait for completion of the SSL shutdown procedure
  276. before aborting the connection. Default is 30s.
  277. start_serving set to True (default) causes the created server
  278. to start accepting connections immediately. When set to False,
  279. the user should await Server.start_serving() or Server.serve_forever()
  280. to make the server to start accepting connections.
  281. """
  282. raise NotImplementedError
  283. async def sendfile(self, transport, file, offset=0, count=None,
  284. *, fallback=True):
  285. """Send a file through a transport.
  286. Return an amount of sent bytes.
  287. """
  288. raise NotImplementedError
  289. async def start_tls(self, transport, protocol, sslcontext, *,
  290. server_side=False,
  291. server_hostname=None,
  292. ssl_handshake_timeout=None,
  293. ssl_shutdown_timeout=None):
  294. """Upgrade a transport to TLS.
  295. Return a new transport that *protocol* should start using
  296. immediately.
  297. """
  298. raise NotImplementedError
  299. async def create_unix_connection(
  300. self, protocol_factory, path=None, *,
  301. ssl=None, sock=None,
  302. server_hostname=None,
  303. ssl_handshake_timeout=None,
  304. ssl_shutdown_timeout=None):
  305. raise NotImplementedError
  306. async def create_unix_server(
  307. self, protocol_factory, path=None, *,
  308. sock=None, backlog=100, ssl=None,
  309. ssl_handshake_timeout=None,
  310. ssl_shutdown_timeout=None,
  311. start_serving=True):
  312. """A coroutine which creates a UNIX Domain Socket server.
  313. The return value is a Server object, which can be used to stop
  314. the service.
  315. path is a str, representing a file system path to bind the
  316. server socket to.
  317. sock can optionally be specified in order to use a preexisting
  318. socket object.
  319. backlog is the maximum number of queued connections passed to
  320. listen() (defaults to 100).
  321. ssl can be set to an SSLContext to enable SSL over the
  322. accepted connections.
  323. ssl_handshake_timeout is the time in seconds that an SSL server
  324. will wait for the SSL handshake to complete (defaults to 60s).
  325. ssl_shutdown_timeout is the time in seconds that an SSL server
  326. will wait for the SSL shutdown to finish (defaults to 30s).
  327. start_serving set to True (default) causes the created server
  328. to start accepting connections immediately. When set to False,
  329. the user should await Server.start_serving() or Server.serve_forever()
  330. to make the server to start accepting connections.
  331. """
  332. raise NotImplementedError
  333. async def connect_accepted_socket(
  334. self, protocol_factory, sock,
  335. *, ssl=None,
  336. ssl_handshake_timeout=None,
  337. ssl_shutdown_timeout=None):
  338. """Handle an accepted connection.
  339. This is used by servers that accept connections outside of
  340. asyncio, but use asyncio to handle connections.
  341. This method is a coroutine. When completed, the coroutine
  342. returns a (transport, protocol) pair.
  343. """
  344. raise NotImplementedError
  345. async def create_datagram_endpoint(self, protocol_factory,
  346. local_addr=None, remote_addr=None, *,
  347. family=0, proto=0, flags=0,
  348. reuse_address=None, reuse_port=None,
  349. allow_broadcast=None, sock=None):
  350. """A coroutine which creates a datagram endpoint.
  351. This method will try to establish the endpoint in the background.
  352. When successful, the coroutine returns a (transport, protocol) pair.
  353. protocol_factory must be a callable returning a protocol instance.
  354. socket family AF_INET, socket.AF_INET6 or socket.AF_UNIX depending on
  355. host (or family if specified), socket type SOCK_DGRAM.
  356. reuse_address tells the kernel to reuse a local socket in
  357. TIME_WAIT state, without waiting for its natural timeout to
  358. expire. If not specified it will automatically be set to True on
  359. UNIX.
  360. reuse_port tells the kernel to allow this endpoint to be bound to
  361. the same port as other existing endpoints are bound to, so long as
  362. they all set this flag when being created. This option is not
  363. supported on Windows and some UNIX's. If the
  364. :py:data:`~socket.SO_REUSEPORT` constant is not defined then this
  365. capability is unsupported.
  366. allow_broadcast tells the kernel to allow this endpoint to send
  367. messages to the broadcast address.
  368. sock can optionally be specified in order to use a preexisting
  369. socket object.
  370. """
  371. raise NotImplementedError
  372. # Pipes and subprocesses.
  373. async def connect_read_pipe(self, protocol_factory, pipe):
  374. """Register read pipe in event loop. Set the pipe to non-blocking mode.
  375. protocol_factory should instantiate object with Protocol interface.
  376. pipe is a file-like object.
  377. Return pair (transport, protocol), where transport supports the
  378. ReadTransport interface."""
  379. # The reason to accept file-like object instead of just file descriptor
  380. # is: we need to own pipe and close it at transport finishing
  381. # Can got complicated errors if pass f.fileno(),
  382. # close fd in pipe transport then close f and vice versa.
  383. raise NotImplementedError
  384. async def connect_write_pipe(self, protocol_factory, pipe):
  385. """Register write pipe in event loop.
  386. protocol_factory should instantiate object with BaseProtocol interface.
  387. Pipe is file-like object already switched to nonblocking.
  388. Return pair (transport, protocol), where transport support
  389. WriteTransport interface."""
  390. # The reason to accept file-like object instead of just file descriptor
  391. # is: we need to own pipe and close it at transport finishing
  392. # Can got complicated errors if pass f.fileno(),
  393. # close fd in pipe transport then close f and vice versa.
  394. raise NotImplementedError
  395. async def subprocess_shell(self, protocol_factory, cmd, *,
  396. stdin=subprocess.PIPE,
  397. stdout=subprocess.PIPE,
  398. stderr=subprocess.PIPE,
  399. **kwargs):
  400. raise NotImplementedError
  401. async def subprocess_exec(self, protocol_factory, *args,
  402. stdin=subprocess.PIPE,
  403. stdout=subprocess.PIPE,
  404. stderr=subprocess.PIPE,
  405. **kwargs):
  406. raise NotImplementedError
  407. # Ready-based callback registration methods.
  408. # The add_*() methods return None.
  409. # The remove_*() methods return True if something was removed,
  410. # False if there was nothing to delete.
  411. def add_reader(self, fd, callback, *args):
  412. raise NotImplementedError
  413. def remove_reader(self, fd):
  414. raise NotImplementedError
  415. def add_writer(self, fd, callback, *args):
  416. raise NotImplementedError
  417. def remove_writer(self, fd):
  418. raise NotImplementedError
  419. # Completion based I/O methods returning Futures.
  420. async def sock_recv(self, sock, nbytes):
  421. raise NotImplementedError
  422. async def sock_recv_into(self, sock, buf):
  423. raise NotImplementedError
  424. async def sock_recvfrom(self, sock, bufsize):
  425. raise NotImplementedError
  426. async def sock_recvfrom_into(self, sock, buf, nbytes=0):
  427. raise NotImplementedError
  428. async def sock_sendall(self, sock, data):
  429. raise NotImplementedError
  430. async def sock_sendto(self, sock, data, address):
  431. raise NotImplementedError
  432. async def sock_connect(self, sock, address):
  433. raise NotImplementedError
  434. async def sock_accept(self, sock):
  435. raise NotImplementedError
  436. async def sock_sendfile(self, sock, file, offset=0, count=None,
  437. *, fallback=None):
  438. raise NotImplementedError
  439. # Signal handling.
  440. def add_signal_handler(self, sig, callback, *args):
  441. raise NotImplementedError
  442. def remove_signal_handler(self, sig):
  443. raise NotImplementedError
  444. # Task factory.
  445. def set_task_factory(self, factory):
  446. raise NotImplementedError
  447. def get_task_factory(self):
  448. raise NotImplementedError
  449. # Error handlers.
  450. def get_exception_handler(self):
  451. raise NotImplementedError
  452. def set_exception_handler(self, handler):
  453. raise NotImplementedError
  454. def default_exception_handler(self, context):
  455. raise NotImplementedError
  456. def call_exception_handler(self, context):
  457. raise NotImplementedError
  458. # Debug flag management.
  459. def get_debug(self):
  460. raise NotImplementedError
  461. def set_debug(self, enabled):
  462. raise NotImplementedError
  463. class AbstractEventLoopPolicy:
  464. """Abstract policy for accessing the event loop."""
  465. def get_event_loop(self):
  466. """Get the event loop for the current context.
  467. Returns an event loop object implementing the BaseEventLoop interface,
  468. or raises an exception in case no event loop has been set for the
  469. current context and the current policy does not specify to create one.
  470. It should never return None."""
  471. raise NotImplementedError
  472. def set_event_loop(self, loop):
  473. """Set the event loop for the current context to loop."""
  474. raise NotImplementedError
  475. def new_event_loop(self):
  476. """Create and return a new event loop object according to this
  477. policy's rules. If there's need to set this loop as the event loop for
  478. the current context, set_event_loop must be called explicitly."""
  479. raise NotImplementedError
  480. # Child processes handling (Unix only).
  481. def get_child_watcher(self):
  482. "Get the watcher for child processes."
  483. raise NotImplementedError
  484. def set_child_watcher(self, watcher):
  485. """Set the watcher for child processes."""
  486. raise NotImplementedError
  487. class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
  488. """Default policy implementation for accessing the event loop.
  489. In this policy, each thread has its own event loop. However, we
  490. only automatically create an event loop by default for the main
  491. thread; other threads by default have no event loop.
  492. Other policies may have different rules (e.g. a single global
  493. event loop, or automatically creating an event loop per thread, or
  494. using some other notion of context to which an event loop is
  495. associated).
  496. """
  497. _loop_factory = None
  498. class _Local(threading.local):
  499. _loop = None
  500. _set_called = False
  501. def __init__(self):
  502. self._local = self._Local()
  503. def get_event_loop(self):
  504. """Get the event loop for the current context.
  505. Returns an instance of EventLoop or raises an exception.
  506. """
  507. if (self._local._loop is None and
  508. not self._local._set_called and
  509. threading.current_thread() is threading.main_thread()):
  510. self.set_event_loop(self.new_event_loop())
  511. if self._local._loop is None:
  512. raise RuntimeError('There is no current event loop in thread %r.'
  513. % threading.current_thread().name)
  514. return self._local._loop
  515. def set_event_loop(self, loop):
  516. """Set the event loop."""
  517. self._local._set_called = True
  518. if loop is not None and not isinstance(loop, AbstractEventLoop):
  519. raise TypeError(f"loop must be an instance of AbstractEventLoop or None, not '{type(loop).__name__}'")
  520. self._local._loop = loop
  521. def new_event_loop(self):
  522. """Create a new event loop.
  523. You must call set_event_loop() to make this the current event
  524. loop.
  525. """
  526. return self._loop_factory()
  527. # Event loop policy. The policy itself is always global, even if the
  528. # policy's rules say that there is an event loop per thread (or other
  529. # notion of context). The default policy is installed by the first
  530. # call to get_event_loop_policy().
  531. _event_loop_policy = None
  532. # Lock for protecting the on-the-fly creation of the event loop policy.
  533. _lock = threading.Lock()
  534. # A TLS for the running event loop, used by _get_running_loop.
  535. class _RunningLoop(threading.local):
  536. loop_pid = (None, None)
  537. _running_loop = _RunningLoop()
  538. def get_running_loop():
  539. """Return the running event loop. Raise a RuntimeError if there is none.
  540. This function is thread-specific.
  541. """
  542. # NOTE: this function is implemented in C (see _asynciomodule.c)
  543. loop = _get_running_loop()
  544. if loop is None:
  545. raise RuntimeError('no running event loop')
  546. return loop
  547. def _get_running_loop():
  548. """Return the running event loop or None.
  549. This is a low-level function intended to be used by event loops.
  550. This function is thread-specific.
  551. """
  552. # NOTE: this function is implemented in C (see _asynciomodule.c)
  553. running_loop, pid = _running_loop.loop_pid
  554. if running_loop is not None and pid == os.getpid():
  555. return running_loop
  556. def _set_running_loop(loop):
  557. """Set the running event loop.
  558. This is a low-level function intended to be used by event loops.
  559. This function is thread-specific.
  560. """
  561. # NOTE: this function is implemented in C (see _asynciomodule.c)
  562. _running_loop.loop_pid = (loop, os.getpid())
  563. def _init_event_loop_policy():
  564. global _event_loop_policy
  565. with _lock:
  566. if _event_loop_policy is None: # pragma: no branch
  567. from . import DefaultEventLoopPolicy
  568. _event_loop_policy = DefaultEventLoopPolicy()
  569. def get_event_loop_policy():
  570. """Get the current event loop policy."""
  571. if _event_loop_policy is None:
  572. _init_event_loop_policy()
  573. return _event_loop_policy
  574. def set_event_loop_policy(policy):
  575. """Set the current event loop policy.
  576. If policy is None, the default policy is restored."""
  577. global _event_loop_policy
  578. if policy is not None and not isinstance(policy, AbstractEventLoopPolicy):
  579. raise TypeError(f"policy must be an instance of AbstractEventLoopPolicy or None, not '{type(policy).__name__}'")
  580. _event_loop_policy = policy
  581. def get_event_loop():
  582. """Return an asyncio event loop.
  583. When called from a coroutine or a callback (e.g. scheduled with call_soon
  584. or similar API), this function will always return the running event loop.
  585. If there is no running event loop set, the function will return
  586. the result of `get_event_loop_policy().get_event_loop()` call.
  587. """
  588. # NOTE: this function is implemented in C (see _asynciomodule.c)
  589. return _py__get_event_loop()
  590. def _get_event_loop(stacklevel=3):
  591. # This internal method is going away in Python 3.12, left here only for
  592. # backwards compatibility with 3.10.0 - 3.10.8 and 3.11.0.
  593. # Similarly, this method's C equivalent in _asyncio is going away as well.
  594. # See GH-99949 for more details.
  595. current_loop = _get_running_loop()
  596. if current_loop is not None:
  597. return current_loop
  598. return get_event_loop_policy().get_event_loop()
  599. def set_event_loop(loop):
  600. """Equivalent to calling get_event_loop_policy().set_event_loop(loop)."""
  601. get_event_loop_policy().set_event_loop(loop)
  602. def new_event_loop():
  603. """Equivalent to calling get_event_loop_policy().new_event_loop()."""
  604. return get_event_loop_policy().new_event_loop()
  605. def get_child_watcher():
  606. """Equivalent to calling get_event_loop_policy().get_child_watcher()."""
  607. return get_event_loop_policy().get_child_watcher()
  608. def set_child_watcher(watcher):
  609. """Equivalent to calling
  610. get_event_loop_policy().set_child_watcher(watcher)."""
  611. return get_event_loop_policy().set_child_watcher(watcher)
  612. # Alias pure-Python implementations for testing purposes.
  613. _py__get_running_loop = _get_running_loop
  614. _py__set_running_loop = _set_running_loop
  615. _py_get_running_loop = get_running_loop
  616. _py_get_event_loop = get_event_loop
  617. _py__get_event_loop = _get_event_loop
  618. try:
  619. # get_event_loop() is one of the most frequently called
  620. # functions in asyncio. Pure Python implementation is
  621. # about 4 times slower than C-accelerated.
  622. from _asyncio import (_get_running_loop, _set_running_loop,
  623. get_running_loop, get_event_loop, _get_event_loop)
  624. except ImportError:
  625. pass
  626. else:
  627. # Alias C implementations for testing purposes.
  628. _c__get_running_loop = _get_running_loop
  629. _c__set_running_loop = _set_running_loop
  630. _c_get_running_loop = get_running_loop
  631. _c_get_event_loop = get_event_loop
  632. _c__get_event_loop = _get_event_loop