events.py 26 KB

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