Debian Codegraph @

Lib/asyncio/events.py

raw
1 """Event loop and event loop policy."""
2
3 # Contains code from https://github.com/MagicStack/uvloop/tree/v0.16.0
4 # SPDX-License-Identifier: PSF-2.0 AND (MIT OR Apache-2.0)
5 # SPDX-FileCopyrightText: Copyright (c) 2015-2021 MagicStack Inc. http://magic.io
6
7 __all__ = (
8 'AbstractEventLoopPolicy',
9 'AbstractEventLoop', 'AbstractServer',
10 'Handle', 'TimerHandle',
11 'get_event_loop_policy', 'set_event_loop_policy',
12 'get_event_loop', 'set_event_loop', 'new_event_loop',
13 'get_child_watcher', 'set_child_watcher',
14 '_set_running_loop', 'get_running_loop',
15 '_get_running_loop',
16 )
17
18 import contextvars
19 import os
20 import signal
21 import socket
22 import subprocess
23 import sys
24 import threading
25
26 from . import format_helpers
27
28
29 class Handle:
30 """Object returned by callback registration methods."""
31
32 __slots__ = ('_callback', '_args', '_cancelled', '_loop',
33 '_source_traceback', '_repr', '__weakref__',
34 '_context')
35
36 def __init__(self, callback, args, loop, context=None):
37 if context is None:
38 context = contextvars.copy_context()
39 self._context = context
40 self._loop = loop
41 self._callback = callback
42 self._args = args
43 self._cancelled = False
44 self._repr = None
45 if self._loop.get_debug():
46 self._source_traceback = format_helpers.extract_stack(
47 sys._getframe(1))
48 else:
49 self._source_traceback = None
50
51 def _repr_info(self):
52 info = [self.__class__.__name__]
53 if self._cancelled:
54 info.append('cancelled')
55 if self._callback is not None:
56 info.append(format_helpers._format_callback_source(
57 self._callback, self._args,
58 debug=self._loop.get_debug()))
59 if self._source_traceback:
60 frame = self._source_traceback[-1]
61 info.append(f'created at {frame[0]}:{frame[1]}')
62 return info
63
64 def __repr__(self):
65 if self._repr is not None:
66 return self._repr
67 info = self._repr_info()
68 return '<{}>'.format(' '.join(info))
69
70 def get_context(self):
71 return self._context
72
73 def cancel(self):
74 if not self._cancelled:
75 self._cancelled = True
76 if self._loop.get_debug():
77 # Keep a representation in debug mode to keep callback and
78 # parameters. For example, to log the warning
79 # "Executing <Handle...> took 2.5 second"
80 self._repr = repr(self)
81 self._callback = None
82 self._args = None
83
84 def cancelled(self):
85 return self._cancelled
86
87 def _run(self):
88 try:
89 self._context.run(self._callback, *self._args)
90 except (SystemExit, KeyboardInterrupt):
91 raise
92 except BaseException as exc:
93 cb = format_helpers._format_callback_source(
94 self._callback, self._args,
95 debug=self._loop.get_debug())
96 msg = f'Exception in callback {cb}'
97 context = {
98 'message': msg,
99 'exception': exc,
100 'handle': self,
101 }
102 if self._source_traceback:
103 context['source_traceback'] = self._source_traceback
104 self._loop.call_exception_handler(context)
105 self = None # Needed to break cycles when an exception occurs.
106
107
108 class TimerHandle(Handle):
109 """Object returned by timed callback registration methods."""
110
111 __slots__ = ['_scheduled', '_when']
112
113 def __init__(self, when, callback, args, loop, context=None):
114 super().__init__(callback, args, loop, context)
115 if self._source_traceback:
116 del self._source_traceback[-1]
117 self._when = when
118 self._scheduled = False
119
120 def _repr_info(self):
121 info = super()._repr_info()
122 pos = 2 if self._cancelled else 1
123 info.insert(pos, f'when={self._when}')
124 return info
125
126 def __hash__(self):
127 return hash(self._when)
128
129 def __lt__(self, other):
130 if isinstance(other, TimerHandle):
131 return self._when < other._when
132 return NotImplemented
133
134 def __le__(self, other):
135 if isinstance(other, TimerHandle):
136 return self._when < other._when or self.__eq__(other)
137 return NotImplemented
138
139 def __gt__(self, other):
140 if isinstance(other, TimerHandle):
141 return self._when > other._when
142 return NotImplemented
143
144 def __ge__(self, other):
145 if isinstance(other, TimerHandle):
146 return self._when > other._when or self.__eq__(other)
147 return NotImplemented
148
149 def __eq__(self, other):
150 if isinstance(other, TimerHandle):
151 return (self._when == other._when and
152 self._callback == other._callback and
153 self._args == other._args and
154 self._cancelled == other._cancelled)
155 return NotImplemented
156
157 def cancel(self):
158 if not self._cancelled:
159 self._loop._timer_handle_cancelled(self)
160 super().cancel()
161
162 def when(self):
163 """Return a scheduled callback time.
164
165 The time is an absolute timestamp, using the same time
166 reference as loop.time().
167 """
168 return self._when
169
170
171 class AbstractServer:
172 """Abstract server returned by create_server()."""
173
174 def close(self):
175 """Stop serving. This leaves existing connections open."""
176 raise NotImplementedError
177
178 def close_clients(self):
179 """Close all active connections."""
180 raise NotImplementedError
181
182 def abort_clients(self):
183 """Close all active connections immediately."""
184 raise NotImplementedError
185
186 def get_loop(self):
187 """Get the event loop the Server object is attached to."""
188 raise NotImplementedError
189
190 def is_serving(self):
191 """Return True if the server is accepting connections."""
192 raise NotImplementedError
193
194 async def start_serving(self):
195 """Start accepting connections.
196
197 This method is idempotent, so it can be called when
198 the server is already being serving.
199 """
200 raise NotImplementedError
201
202 async def serve_forever(self):
203 """Start accepting connections until the coroutine is cancelled.
204
205 The server is closed when the coroutine is cancelled.
206 """
207 raise NotImplementedError
208
209 async def wait_closed(self):
210 """Coroutine to wait until service is closed."""
211 raise NotImplementedError
212
213 async def __aenter__(self):
214 return self
215
216 async def __aexit__(self, *exc):
217 self.close()
218 await self.wait_closed()
219
220
221 class AbstractEventLoop:
222 """Abstract event loop."""
223
224 # Running and stopping the event loop.
225
226 def run_forever(self):
227 """Run the event loop until stop() is called."""
228 raise NotImplementedError
229
230 def run_until_complete(self, future):
231 """Run the event loop until a Future is done.
232
233 Return the Future's result, or raise its exception.
234 """
235 raise NotImplementedError
236
237 def stop(self):
238 """Stop the event loop as soon as reasonable.
239
240 Exactly how soon that is may depend on the implementation, but
241 no more I/O callbacks should be scheduled.
242 """
243 raise NotImplementedError
244
245 def is_running(self):
246 """Return whether the event loop is currently running."""
247 raise NotImplementedError
248
249 def is_closed(self):
250 """Returns True if the event loop was closed."""
251 raise NotImplementedError
252
253 def close(self):
254 """Close the loop.
255
256 The loop should not be running.
257
258 This is idempotent and irreversible.
259
260 No other methods should be called after this one.
261 """
262 raise NotImplementedError
263
264 async def shutdown_asyncgens(self):
265 """Shutdown all active asynchronous generators."""
266 raise NotImplementedError
267
268 async def shutdown_default_executor(self):
269 """Schedule the shutdown of the default executor."""
270 raise NotImplementedError
271
272 # Methods scheduling callbacks. All these return Handles.
273
274 def _timer_handle_cancelled(self, handle):
275 """Notification that a TimerHandle has been cancelled."""
276 raise NotImplementedError
277
278 def call_soon(self, callback, *args, context=None):
279 return self.call_later(0, callback, *args, context=context)
280
281 def call_later(self, delay, callback, *args, context=None):
282 raise NotImplementedError
283
284 def call_at(self, when, callback, *args, context=None):
285 raise NotImplementedError
286
287 def time(self):
288 raise NotImplementedError
289
290 def create_future(self):
291 raise NotImplementedError
292
293 # Method scheduling a coroutine object: create a task.
294
295 def create_task(self, coro, **kwargs):
296 raise NotImplementedError
297
298 # Methods for interacting with threads.
299
300 def call_soon_threadsafe(self, callback, *args, context=None):
301 raise NotImplementedError
302
303 def run_in_executor(self, executor, func, *args):
304 raise NotImplementedError
305
306 def set_default_executor(self, executor):
307 raise NotImplementedError
308
309 # Network I/O methods returning Futures.
310
311 async def getaddrinfo(self, host, port, *,
312 family=0, type=0, proto=0, flags=0):
313 raise NotImplementedError
314
315 async def getnameinfo(self, sockaddr, flags=0):
316 raise NotImplementedError
317
318 async def create_connection(
319 self, protocol_factory, host=None, port=None,
320 *, ssl=None, family=0, proto=0,
321 flags=0, sock=None, local_addr=None,
322 server_hostname=None,
323 ssl_handshake_timeout=None,
324 ssl_shutdown_timeout=None,
325 happy_eyeballs_delay=None, interleave=None):
326 raise NotImplementedError
327
328 async def create_server(
329 self, protocol_factory, host=None, port=None,
330 *, family=socket.AF_UNSPEC,
331 flags=socket.AI_PASSIVE, sock=None, backlog=100,
332 ssl=None, reuse_address=None, reuse_port=None,
333 keep_alive=None,
334 ssl_handshake_timeout=None,
335 ssl_shutdown_timeout=None,
336 start_serving=True):
337 """A coroutine which creates a TCP server bound to host and port.
338
339 The return value is a Server object which can be used to stop
340 the service.
341
342 If host is an empty string or None all interfaces are assumed
343 and a list of multiple sockets will be returned (most likely
344 one for IPv4 and another one for IPv6). The host parameter can also
345 be a sequence (e.g. list) of hosts to bind to.
346
347 family can be set to either AF_INET or AF_INET6 to force the
348 socket to use IPv4 or IPv6. If not set it will be determined
349 from host (defaults to AF_UNSPEC).
350
351 flags is a bitmask for getaddrinfo().
352
353 sock can optionally be specified in order to use a preexisting
354 socket object.
355
356 backlog is the maximum number of queued connections passed to
357 listen() (defaults to 100).
358
359 ssl can be set to an SSLContext to enable SSL over the
360 accepted connections.
361
362 reuse_address tells the kernel to reuse a local socket in
363 TIME_WAIT state, without waiting for its natural timeout to
364 expire. If not specified will automatically be set to True on
365 UNIX.
366
367 reuse_port tells the kernel to allow this endpoint to be bound to
368 the same port as other existing endpoints are bound to, so long as
369 they all set this flag when being created. This option is not
370 supported on Windows.
371
372 keep_alive set to True keeps connections active by enabling the
373 periodic transmission of messages.
374
375 ssl_handshake_timeout is the time in seconds that an SSL server
376 will wait for completion of the SSL handshake before aborting the
377 connection. Default is 60s.
378
379 ssl_shutdown_timeout is the time in seconds that an SSL server
380 will wait for completion of the SSL shutdown procedure
381 before aborting the connection. Default is 30s.
382
383 start_serving set to True (default) causes the created server
384 to start accepting connections immediately. When set to False,
385 the user should await Server.start_serving() or
386 Server.serve_forever() to make the server to start accepting
387 connections.
388 """
389 raise NotImplementedError
390
391 async def sendfile(self, transport, file, offset=0, count=None,
392 *, fallback=True):
393 """Send a file through a transport.
394
395 Return an amount of sent bytes.
396 """
397 raise NotImplementedError
398
399 async def start_tls(self, transport, protocol, sslcontext, *,
400 server_side=False,
401 server_hostname=None,
402 ssl_handshake_timeout=None,
403 ssl_shutdown_timeout=None):
404 """Upgrade a transport to TLS.
405
406 Return a new transport that *protocol* should start using
407 immediately.
408 """
409 raise NotImplementedError
410
411 async def create_unix_connection(
412 self, protocol_factory, path=None, *,
413 ssl=None, sock=None,
414 server_hostname=None,
415 ssl_handshake_timeout=None,
416 ssl_shutdown_timeout=None):
417 raise NotImplementedError
418
419 async def create_unix_server(
420 self, protocol_factory, path=None, *,
421 sock=None, backlog=100, ssl=None,
422 ssl_handshake_timeout=None,
423 ssl_shutdown_timeout=None,
424 start_serving=True):
425 """A coroutine which creates a UNIX Domain Socket server.
426
427 The return value is a Server object, which can be used to stop
428 the service.
429
430 path is a str, representing a file system path to bind the
431 server socket to.
432
433 sock can optionally be specified in order to use a preexisting
434 socket object.
435
436 backlog is the maximum number of queued connections passed to
437 listen() (defaults to 100).
438
439 ssl can be set to an SSLContext to enable SSL over the
440 accepted connections.
441
442 ssl_handshake_timeout is the time in seconds that an SSL server
443 will wait for the SSL handshake to complete (defaults to 60s).
444
445 ssl_shutdown_timeout is the time in seconds that an SSL server
446 will wait for the SSL shutdown to finish (defaults to 30s).
447
448 start_serving set to True (default) causes the created server
449 to start accepting connections immediately. When set to False,
450 the user should await Server.start_serving() or
451 Server.serve_forever() to make the server to start accepting
452 connections.
453 """
454 raise NotImplementedError
455
456 async def connect_accepted_socket(
457 self, protocol_factory, sock,
458 *, ssl=None,
459 ssl_handshake_timeout=None,
460 ssl_shutdown_timeout=None):
461 """Handle an accepted connection.
462
463 This is used by servers that accept connections outside of
464 asyncio, but use asyncio to handle connections.
465
466 This method is a coroutine. When completed, the coroutine
467 returns a (transport, protocol) pair.
468 """
469 raise NotImplementedError
470
471 async def create_datagram_endpoint(self, protocol_factory,
472 local_addr=None, remote_addr=None, *,
473 family=0, proto=0, flags=0,
474 reuse_address=None, reuse_port=None,
475 allow_broadcast=None, sock=None):
476 """A coroutine which creates a datagram endpoint.
477
478 This method will try to establish the endpoint in the background.
479 When successful, the coroutine returns a (transport, protocol) pair.
480
481 protocol_factory must be a callable returning a protocol instance.
482
483 socket family AF_INET, socket.AF_INET6 or socket.AF_UNIX depending
484 on host (or family if specified), socket type SOCK_DGRAM.
485
486 reuse_address tells the kernel to reuse a local socket in
487 TIME_WAIT state, without waiting for its natural timeout to
488 expire. If not specified it will automatically be set to True on
489 UNIX.
490
491 reuse_port tells the kernel to allow this endpoint to be bound to
492 the same port as other existing endpoints are bound to, so long as
493 they all set this flag when being created. This option is not
494 supported on Windows and some UNIX's. If the
495 :py:data:`~socket.SO_REUSEPORT` constant is not defined then this
496 capability is unsupported.
497
498 allow_broadcast tells the kernel to allow this endpoint to send
499 messages to the broadcast address.
500
501 sock can optionally be specified in order to use a preexisting
502 socket object.
503 """
504 raise NotImplementedError
505
506 # Pipes and subprocesses.
507
508 async def connect_read_pipe(self, protocol_factory, pipe):
509 """Register read pipe in event loop. Set the pipe to non-blocking mode.
510
511 protocol_factory should instantiate object with Protocol interface.
512 pipe is a file-like object.
513 Return pair (transport, protocol), where transport supports the
514 ReadTransport interface."""
515 # The reason to accept file-like object instead of just file descriptor
516 # is: we need to own pipe and close it at transport finishing
517 # Can got complicated errors if pass f.fileno(),
518 # close fd in pipe transport then close f and vice versa.
519 raise NotImplementedError
520
521 async def connect_write_pipe(self, protocol_factory, pipe):
522 """Register write pipe in event loop.
523
524 protocol_factory should instantiate object with BaseProtocol
525 interface.
526 Pipe is file-like object already switched to nonblocking.
527 Return pair (transport, protocol), where transport support
528 WriteTransport interface."""
529 # The reason to accept file-like object instead of just file descriptor
530 # is: we need to own pipe and close it at transport finishing
531 # Can got complicated errors if pass f.fileno(),
532 # close fd in pipe transport then close f and vice versa.
533 raise NotImplementedError
534
535 async def subprocess_shell(self, protocol_factory, cmd, *,
536 stdin=subprocess.PIPE,
537 stdout=subprocess.PIPE,
538 stderr=subprocess.PIPE,
539 **kwargs):
540 raise NotImplementedError
541
542 async def subprocess_exec(self, protocol_factory, *args,
543 stdin=subprocess.PIPE,
544 stdout=subprocess.PIPE,
545 stderr=subprocess.PIPE,
546 **kwargs):
547 raise NotImplementedError
548
549 # Ready-based callback registration methods.
550 # The add_*() methods return None.
551 # The remove_*() methods return True if something was removed,
552 # False if there was nothing to delete.
553
554 def add_reader(self, fd, callback, *args):
555 raise NotImplementedError
556
557 def remove_reader(self, fd):
558 raise NotImplementedError
559
560 def add_writer(self, fd, callback, *args):
561 raise NotImplementedError
562
563 def remove_writer(self, fd):
564 raise NotImplementedError
565
566 # Completion based I/O methods returning Futures.
567
568 async def sock_recv(self, sock, nbytes):
569 raise NotImplementedError
570
571 async def sock_recv_into(self, sock, buf):
572 raise NotImplementedError
573
574 async def sock_recvfrom(self, sock, bufsize):
575 raise NotImplementedError
576
577 async def sock_recvfrom_into(self, sock, buf, nbytes=0):
578 raise NotImplementedError
579
580 async def sock_sendall(self, sock, data):
581 raise NotImplementedError
582
583 async def sock_sendto(self, sock, data, address):
584 raise NotImplementedError
585
586 async def sock_connect(self, sock, address):
587 raise NotImplementedError
588
589 async def sock_accept(self, sock):
590 raise NotImplementedError
591
592 async def sock_sendfile(self, sock, file, offset=0, count=None,
593 *, fallback=None):
594 raise NotImplementedError
595
596 # Signal handling.
597
598 def add_signal_handler(self, sig, callback, *args):
599 raise NotImplementedError
600
601 def remove_signal_handler(self, sig):
602 raise NotImplementedError
603
604 # Task factory.
605
606 def set_task_factory(self, factory):
607 raise NotImplementedError
608
609 def get_task_factory(self):
610 raise NotImplementedError
611
612 # Error handlers.
613
614 def get_exception_handler(self):
615 raise NotImplementedError
616
617 def set_exception_handler(self, handler):
618 raise NotImplementedError
619
620 def default_exception_handler(self, context):
621 raise NotImplementedError
622
623 def call_exception_handler(self, context):
624 raise NotImplementedError
625
626 # Debug flag management.
627
628 def get_debug(self):
629 raise NotImplementedError
630
631 def set_debug(self, enabled):
632 raise NotImplementedError
633
634
635 class AbstractEventLoopPolicy:
636 """Abstract policy for accessing the event loop."""
637
638 def get_event_loop(self):
639 """Get the event loop for the current context.
640
641 Returns an event loop object implementing the AbstractEventLoop interface,
642 or raises an exception in case no event loop has been set for the
643 current context and the current policy does not specify to create one.
644
645 It should never return None."""
646 raise NotImplementedError
647
648 def set_event_loop(self, loop):
649 """Set the event loop for the current context to loop."""
650 raise NotImplementedError
651
652 def new_event_loop(self):
653 """Create and return a new event loop object according to this
654 policy's rules. If there's need to set this loop as the event loop for
655 the current context, set_event_loop must be called explicitly."""
656 raise NotImplementedError
657
658 # Child processes handling (Unix only).
659
660 def get_child_watcher(self):
661 "Get the watcher for child processes."
662 raise NotImplementedError
663
664 def set_child_watcher(self, watcher):
665 """Set the watcher for child processes."""
666 raise NotImplementedError
667
668
669 class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
670 """Default policy implementation for accessing the event loop.
671
672 In this policy, each thread has its own event loop. However, we
673 only automatically create an event loop by default for the main
674 thread; other threads by default have no event loop.
675
676 Other policies may have different rules (e.g. a single global
677 event loop, or automatically creating an event loop per thread, or
678 using some other notion of context to which an event loop is
679 associated).
680 """
681
682 _loop_factory = None
683
684 class _Local(threading.local):
685 _loop = None
686 _set_called = False
687
688 def __init__(self):
689 self._local = self._Local()
690
691 def get_event_loop(self):
692 """Get the event loop for the current context.
693
694 Returns an instance of EventLoop or raises an exception.
695 """
696 if (self._local._loop is None and
697 not self._local._set_called and
698 threading.current_thread() is threading.main_thread()):
699 stacklevel = 2
700 try:
701 f = sys._getframe(1)
702 except AttributeError:
703 pass
704 else:
705 # Move up the call stack so that the warning is attached
706 # to the line outside asyncio itself.
707 while f:
708 module = f.f_globals.get('__name__')
709 if not (module == 'asyncio' or module.startswith('asyncio.')):
710 break
711 f = f.f_back
712 stacklevel += 1
713 import warnings
714 warnings.warn('There is no current event loop',
715 DeprecationWarning, stacklevel=stacklevel)
716 self.set_event_loop(self.new_event_loop())
717
718 if self._local._loop is None:
719 raise RuntimeError('There is no current event loop in thread %r.'
720 % threading.current_thread().name)
721
722 return self._local._loop
723
724 def set_event_loop(self, loop):
725 """Set the event loop."""
726 self._local._set_called = True
727 if loop is not None and not isinstance(loop, AbstractEventLoop):
728 raise TypeError(f"loop must be an instance of AbstractEventLoop or None, not '{type(loop).__name__}'")
729 self._local._loop = loop
730
731 def new_event_loop(self):
732 """Create a new event loop.
733
734 You must call set_event_loop() to make this the current event
735 loop.
736 """
737 return self._loop_factory()
738
739
740 # Event loop policy. The policy itself is always global, even if the
741 # policy's rules say that there is an event loop per thread (or other
742 # notion of context). The default policy is installed by the first
743 # call to get_event_loop_policy().
744 _event_loop_policy = None
745
746 # Lock for protecting the on-the-fly creation of the event loop policy.
747 _lock = threading.Lock()
748
749
750 # A TLS for the running event loop, used by _get_running_loop.
751 class _RunningLoop(threading.local):
752 loop_pid = (None, None)
753
754
755 _running_loop = _RunningLoop()
756
757
758 def get_running_loop():
759 """Return the running event loop. Raise a RuntimeError if there is none.
760
761 This function is thread-specific.
762 """
763 # NOTE: this function is implemented in C (see _asynciomodule.c)
764 loop = _get_running_loop()
765 if loop is None:
766 raise RuntimeError('no running event loop')
767 return loop
768
769
770 def _get_running_loop():
771 """Return the running event loop or None.
772
773 This is a low-level function intended to be used by event loops.
774 This function is thread-specific.
775 """
776 # NOTE: this function is implemented in C (see _asynciomodule.c)
777 running_loop, pid = _running_loop.loop_pid
778 if running_loop is not None and pid == os.getpid():
779 return running_loop
780
781
782 def _set_running_loop(loop):
783 """Set the running event loop.
784
785 This is a low-level function intended to be used by event loops.
786 This function is thread-specific.
787 """
788 # NOTE: this function is implemented in C (see _asynciomodule.c)
789 _running_loop.loop_pid = (loop, os.getpid())
790
791
792 def _init_event_loop_policy():
793 global _event_loop_policy
794 with _lock:
795 if _event_loop_policy is None: # pragma: no branch
796 from . import DefaultEventLoopPolicy
797 _event_loop_policy = DefaultEventLoopPolicy()
798
799
800 def get_event_loop_policy():
801 """Get the current event loop policy."""
802 if _event_loop_policy is None:
803 _init_event_loop_policy()
804 return _event_loop_policy
805
806
807 def set_event_loop_policy(policy):
808 """Set the current event loop policy.
809
810 If policy is None, the default policy is restored."""
811 global _event_loop_policy
812 if policy is not None and not isinstance(policy, AbstractEventLoopPolicy):
813 raise TypeError(f"policy must be an instance of AbstractEventLoopPolicy or None, not '{type(policy).__name__}'")
814 _event_loop_policy = policy
815
816
817 def get_event_loop():
818 """Return an asyncio event loop.
819
820 When called from a coroutine or a callback (e.g. scheduled with call_soon
821 or similar API), this function will always return the running event loop.
822
823 If there is no running event loop set, the function will return
824 the result of `get_event_loop_policy().get_event_loop()` call.
825 """
826 # NOTE: this function is implemented in C (see _asynciomodule.c)
827 current_loop = _get_running_loop()
828 if current_loop is not None:
829 return current_loop
830 return get_event_loop_policy().get_event_loop()
831
832
833 def set_event_loop(loop):
834 """Equivalent to calling get_event_loop_policy().set_event_loop(loop)."""
835 get_event_loop_policy().set_event_loop(loop)
836
837
838 def new_event_loop():
839 """Equivalent to calling get_event_loop_policy().new_event_loop()."""
840 return get_event_loop_policy().new_event_loop()
841
842
843 def get_child_watcher():
844 """Equivalent to calling get_event_loop_policy().get_child_watcher()."""
845 return get_event_loop_policy().get_child_watcher()
846
847
848 def set_child_watcher(watcher):
849 """Equivalent to calling
850 get_event_loop_policy().set_child_watcher(watcher)."""
851 return get_event_loop_policy().set_child_watcher(watcher)
852
853
854 # Alias pure-Python implementations for testing purposes.
855 _py__get_running_loop = _get_running_loop
856 _py__set_running_loop = _set_running_loop
857 _py_get_running_loop = get_running_loop
858 _py_get_event_loop = get_event_loop
859
860
861 try:
862 # get_event_loop() is one of the most frequently called
863 # functions in asyncio. Pure Python implementation is
864 # about 4 times slower than C-accelerated.
865 from _asyncio import (_get_running_loop, _set_running_loop,
866 get_running_loop, get_event_loop)
867 except ImportError:
868 pass
869 else:
870 # Alias C implementations for testing purposes.
871 _c__get_running_loop = _get_running_loop
872 _c__set_running_loop = _set_running_loop
873 _c_get_running_loop = get_running_loop
874 _c_get_event_loop = get_event_loop
875
876
877 if hasattr(os, 'fork'):
878 def on_fork():
879 # Reset the loop and wakeupfd in the forked child process.
880 if _event_loop_policy is not None:
881 _event_loop_policy._local = BaseDefaultEventLoopPolicy._Local()
882 _set_running_loop(None)
883 signal.set_wakeup_fd(-1)
884
885 os.register_at_fork(after_in_child=on_fork)