blob: 8a7bb814a31939daa8931861d0e71f1af819ce03 [file] [log] [blame]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07001"""Event loop and event loop policy."""
2
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -08003__all__ = ['AbstractEventLoopPolicy',
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07004 'AbstractEventLoop', 'AbstractServer',
5 'Handle', 'TimerHandle',
6 'get_event_loop_policy', 'set_event_loop_policy',
7 'get_event_loop', 'set_event_loop', 'new_event_loop',
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -08008 'get_child_watcher', 'set_child_watcher',
Guido van Rossum27b7c7e2013-10-17 13:40:50 -07009 ]
10
Victor Stinner307bccc2014-06-12 18:39:26 +020011import functools
12import inspect
Victor Stinner313a9802014-07-29 12:58:23 +020013import reprlib
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070014import socket
Victor Stinner313a9802014-07-29 12:58:23 +020015import subprocess
Victor Stinner307bccc2014-06-12 18:39:26 +020016import sys
Victor Stinner313a9802014-07-29 12:58:23 +020017import threading
18import traceback
Victor Stinner307bccc2014-06-12 18:39:26 +020019
20
21_PY34 = sys.version_info >= (3, 4)
22
Victor Stinner975735f2014-06-25 21:41:58 +020023
Victor Stinner307bccc2014-06-12 18:39:26 +020024def _get_function_source(func):
25 if _PY34:
26 func = inspect.unwrap(func)
27 elif hasattr(func, '__wrapped__'):
28 func = func.__wrapped__
29 if inspect.isfunction(func):
30 code = func.__code__
31 return (code.co_filename, code.co_firstlineno)
32 if isinstance(func, functools.partial):
33 return _get_function_source(func.func)
34 if _PY34 and isinstance(func, functools.partialmethod):
35 return _get_function_source(func.func)
36 return None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070037
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070038
Victor Stinner975735f2014-06-25 21:41:58 +020039def _format_args(args):
Victor Stinner313a9802014-07-29 12:58:23 +020040 """Format function arguments.
41
42 Special case for a single parameter: ('hello',) is formatted as ('hello').
43 """
44 # use reprlib to limit the length of the output
45 args_repr = reprlib.repr(args)
Victor Stinner975735f2014-06-25 21:41:58 +020046 if len(args) == 1 and args_repr.endswith(',)'):
47 args_repr = args_repr[:-2] + ')'
48 return args_repr
49
50
51def _format_callback(func, args, suffix=''):
52 if isinstance(func, functools.partial):
53 if args is not None:
54 suffix = _format_args(args) + suffix
55 return _format_callback(func.func, func.args, suffix)
56
57 func_repr = getattr(func, '__qualname__', None)
58 if not func_repr:
59 func_repr = repr(func)
60
61 if args is not None:
62 func_repr += _format_args(args)
63 if suffix:
64 func_repr += suffix
65
66 source = _get_function_source(func)
67 if source:
68 func_repr += ' at %s:%s' % source
69 return func_repr
70
71
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070072class Handle:
73 """Object returned by callback registration methods."""
74
Victor Stinner80f53aa2014-06-27 13:52:20 +020075 __slots__ = ('_callback', '_args', '_cancelled', '_loop',
Victor Stinner1b38bc62014-09-17 23:24:13 +020076 '_source_traceback', '_repr', '__weakref__')
Yury Selivanovb1317782014-02-12 17:01:52 -050077
Yury Selivanov569efa22014-02-18 18:02:19 -050078 def __init__(self, callback, args, loop):
Victor Stinnerdc62b7e2014-02-10 00:45:44 +010079 assert not isinstance(callback, Handle), 'A Handle is not a callback'
Yury Selivanov569efa22014-02-18 18:02:19 -050080 self._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070081 self._callback = callback
82 self._args = args
83 self._cancelled = False
Victor Stinner1b38bc62014-09-17 23:24:13 +020084 self._repr = None
Victor Stinner80f53aa2014-06-27 13:52:20 +020085 if self._loop.get_debug():
86 self._source_traceback = traceback.extract_stack(sys._getframe(1))
87 else:
88 self._source_traceback = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070089
Victor Stinner1b38bc62014-09-17 23:24:13 +020090 def _repr_info(self):
Victor Stinnerf68bd882014-07-10 22:32:58 +020091 info = [self.__class__.__name__]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070092 if self._cancelled:
Victor Stinner975735f2014-06-25 21:41:58 +020093 info.append('cancelled')
Victor Stinnerf68bd882014-07-10 22:32:58 +020094 if self._callback is not None:
95 info.append(_format_callback(self._callback, self._args))
96 if self._source_traceback:
97 frame = self._source_traceback[-1]
98 info.append('created at %s:%s' % (frame[0], frame[1]))
Victor Stinner1b38bc62014-09-17 23:24:13 +020099 return info
100
101 def __repr__(self):
102 if self._repr is not None:
103 return self._repr
104 info = self._repr_info()
Victor Stinnerf68bd882014-07-10 22:32:58 +0200105 return '<%s>' % ' '.join(info)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700106
107 def cancel(self):
Yury Selivanov592ada92014-09-25 12:07:56 -0400108 if not self._cancelled:
109 self._cancelled = True
110 if self._loop.get_debug():
111 # Keep a representation in debug mode to keep callback and
112 # parameters. For example, to log the warning
113 # "Executing <Handle...> took 2.5 second"
114 self._repr = repr(self)
115 self._callback = None
116 self._args = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700117
118 def _run(self):
119 try:
120 self._callback(*self._args)
Yury Selivanov569efa22014-02-18 18:02:19 -0500121 except Exception as exc:
Victor Stinner17b53f12014-06-26 01:35:45 +0200122 cb = _format_callback(self._callback, self._args)
123 msg = 'Exception in callback {}'.format(cb)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200124 context = {
Yury Selivanov569efa22014-02-18 18:02:19 -0500125 'message': msg,
126 'exception': exc,
127 'handle': self,
Victor Stinner80f53aa2014-06-27 13:52:20 +0200128 }
129 if self._source_traceback:
130 context['source_traceback'] = self._source_traceback
131 self._loop.call_exception_handler(context)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700132 self = None # Needed to break cycles when an exception occurs.
133
134
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700135class TimerHandle(Handle):
136 """Object returned by timed callback registration methods."""
137
Yury Selivanov592ada92014-09-25 12:07:56 -0400138 __slots__ = ['_scheduled', '_when']
Yury Selivanovb1317782014-02-12 17:01:52 -0500139
Yury Selivanov569efa22014-02-18 18:02:19 -0500140 def __init__(self, when, callback, args, loop):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700141 assert when is not None
Yury Selivanov569efa22014-02-18 18:02:19 -0500142 super().__init__(callback, args, loop)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200143 if self._source_traceback:
144 del self._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700145 self._when = when
Yury Selivanov592ada92014-09-25 12:07:56 -0400146 self._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700147
Victor Stinner1b38bc62014-09-17 23:24:13 +0200148 def _repr_info(self):
149 info = super()._repr_info()
150 pos = 2 if self._cancelled else 1
151 info.insert(pos, 'when=%s' % self._when)
152 return info
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700153
154 def __hash__(self):
155 return hash(self._when)
156
157 def __lt__(self, other):
158 return self._when < other._when
159
160 def __le__(self, other):
161 if self._when < other._when:
162 return True
163 return self.__eq__(other)
164
165 def __gt__(self, other):
166 return self._when > other._when
167
168 def __ge__(self, other):
169 if self._when > other._when:
170 return True
171 return self.__eq__(other)
172
173 def __eq__(self, other):
174 if isinstance(other, TimerHandle):
175 return (self._when == other._when and
176 self._callback == other._callback and
177 self._args == other._args and
178 self._cancelled == other._cancelled)
179 return NotImplemented
180
181 def __ne__(self, other):
182 equal = self.__eq__(other)
183 return NotImplemented if equal is NotImplemented else not equal
184
Yury Selivanov592ada92014-09-25 12:07:56 -0400185 def cancel(self):
186 if not self._cancelled:
187 self._loop._timer_handle_cancelled(self)
188 super().cancel()
189
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700190
191class AbstractServer:
Victor Stinnercf6f72e2013-12-03 18:23:52 +0100192 """Abstract server returned by create_server()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700193
194 def close(self):
195 """Stop serving. This leaves existing connections open."""
196 return NotImplemented
197
198 def wait_closed(self):
199 """Coroutine to wait until service is closed."""
200 return NotImplemented
201
202
203class AbstractEventLoop:
204 """Abstract event loop."""
205
206 # Running and stopping the event loop.
207
208 def run_forever(self):
209 """Run the event loop until stop() is called."""
210 raise NotImplementedError
211
212 def run_until_complete(self, future):
213 """Run the event loop until a Future is done.
214
215 Return the Future's result, or raise its exception.
216 """
217 raise NotImplementedError
218
219 def stop(self):
220 """Stop the event loop as soon as reasonable.
221
222 Exactly how soon that is may depend on the implementation, but
223 no more I/O callbacks should be scheduled.
224 """
225 raise NotImplementedError
226
227 def is_running(self):
228 """Return whether the event loop is currently running."""
229 raise NotImplementedError
230
Victor Stinner896a25a2014-07-08 11:29:25 +0200231 def is_closed(self):
232 """Returns True if the event loop was closed."""
233 raise NotImplementedError
234
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700235 def close(self):
236 """Close the loop.
237
238 The loop should not be running.
239
240 This is idempotent and irreversible.
241
242 No other methods should be called after this one.
243 """
244 raise NotImplementedError
245
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700246 # Methods scheduling callbacks. All these return Handles.
247
Yury Selivanov592ada92014-09-25 12:07:56 -0400248 def _timer_handle_cancelled(self, handle):
249 """Notification that a TimerHandle has been cancelled."""
250 raise NotImplementedError
251
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700252 def call_soon(self, callback, *args):
253 return self.call_later(0, callback, *args)
254
255 def call_later(self, delay, callback, *args):
256 raise NotImplementedError
257
258 def call_at(self, when, callback, *args):
259 raise NotImplementedError
260
261 def time(self):
262 raise NotImplementedError
263
Victor Stinner896a25a2014-07-08 11:29:25 +0200264 # Method scheduling a coroutine object: create a task.
265
266 def create_task(self, coro):
267 raise NotImplementedError
268
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700269 # Methods for interacting with threads.
270
271 def call_soon_threadsafe(self, callback, *args):
272 raise NotImplementedError
273
274 def run_in_executor(self, executor, callback, *args):
275 raise NotImplementedError
276
277 def set_default_executor(self, executor):
278 raise NotImplementedError
279
280 # Network I/O methods returning Futures.
281
282 def getaddrinfo(self, host, port, *, family=0, type=0, proto=0, flags=0):
283 raise NotImplementedError
284
285 def getnameinfo(self, sockaddr, flags=0):
286 raise NotImplementedError
287
288 def create_connection(self, protocol_factory, host=None, port=None, *,
289 ssl=None, family=0, proto=0, flags=0, sock=None,
Guido van Rossum21c85a72013-11-01 14:16:54 -0700290 local_addr=None, server_hostname=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700291 raise NotImplementedError
292
293 def create_server(self, protocol_factory, host=None, port=None, *,
294 family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE,
295 sock=None, backlog=100, ssl=None, reuse_address=None):
296 """A coroutine which creates a TCP server bound to host and port.
297
298 The return value is a Server object which can be used to stop
299 the service.
300
301 If host is an empty string or None all interfaces are assumed
302 and a list of multiple sockets will be returned (most likely
303 one for IPv4 and another one for IPv6).
304
305 family can be set to either AF_INET or AF_INET6 to force the
306 socket to use IPv4 or IPv6. If not set it will be determined
307 from host (defaults to AF_UNSPEC).
308
309 flags is a bitmask for getaddrinfo().
310
311 sock can optionally be specified in order to use a preexisting
312 socket object.
313
314 backlog is the maximum number of queued connections passed to
315 listen() (defaults to 100).
316
317 ssl can be set to an SSLContext to enable SSL over the
318 accepted connections.
319
320 reuse_address tells the kernel to reuse a local socket in
321 TIME_WAIT state, without waiting for its natural timeout to
322 expire. If not specified will automatically be set to True on
323 UNIX.
324 """
325 raise NotImplementedError
326
Yury Selivanovb057c522014-02-18 12:15:06 -0500327 def create_unix_connection(self, protocol_factory, path, *,
328 ssl=None, sock=None,
329 server_hostname=None):
330 raise NotImplementedError
331
332 def create_unix_server(self, protocol_factory, path, *,
333 sock=None, backlog=100, ssl=None):
334 """A coroutine which creates a UNIX Domain Socket server.
335
Yury Selivanovdec1a452014-02-18 22:27:48 -0500336 The return value is a Server object, which can be used to stop
Yury Selivanovb057c522014-02-18 12:15:06 -0500337 the service.
338
339 path is a str, representing a file systsem path to bind the
340 server socket to.
341
342 sock can optionally be specified in order to use a preexisting
343 socket object.
344
345 backlog is the maximum number of queued connections passed to
346 listen() (defaults to 100).
347
348 ssl can be set to an SSLContext to enable SSL over the
349 accepted connections.
350 """
351 raise NotImplementedError
352
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700353 def create_datagram_endpoint(self, protocol_factory,
354 local_addr=None, remote_addr=None, *,
355 family=0, proto=0, flags=0):
356 raise NotImplementedError
357
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700358 # Pipes and subprocesses.
359
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700360 def connect_read_pipe(self, protocol_factory, pipe):
Victor Stinnera5b257a2014-05-29 00:14:03 +0200361 """Register read pipe in event loop. Set the pipe to non-blocking mode.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700362
363 protocol_factory should instantiate object with Protocol interface.
Victor Stinnera5b257a2014-05-29 00:14:03 +0200364 pipe is a file-like object.
365 Return pair (transport, protocol), where transport supports the
Guido van Rossum9204af42013-11-30 15:35:42 -0800366 ReadTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700367 # 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
373 def connect_write_pipe(self, protocol_factory, pipe):
Yury Selivanovdec1a452014-02-18 22:27:48 -0500374 """Register write pipe in event loop.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700375
376 protocol_factory should instantiate object with BaseProtocol interface.
377 Pipe is file-like object already switched to nonblocking.
378 Return pair (transport, protocol), where transport support
Guido van Rossum9204af42013-11-30 15:35:42 -0800379 WriteTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700380 # The reason to accept file-like object instead of just file descriptor
381 # is: we need to own pipe and close it at transport finishing
382 # Can got complicated errors if pass f.fileno(),
383 # close fd in pipe transport then close f and vise versa.
384 raise NotImplementedError
385
386 def subprocess_shell(self, protocol_factory, cmd, *, stdin=subprocess.PIPE,
387 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
388 **kwargs):
389 raise NotImplementedError
390
391 def subprocess_exec(self, protocol_factory, *args, stdin=subprocess.PIPE,
392 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
393 **kwargs):
394 raise NotImplementedError
395
396 # Ready-based callback registration methods.
397 # The add_*() methods return None.
398 # The remove_*() methods return True if something was removed,
399 # False if there was nothing to delete.
400
401 def add_reader(self, fd, callback, *args):
402 raise NotImplementedError
403
404 def remove_reader(self, fd):
405 raise NotImplementedError
406
407 def add_writer(self, fd, callback, *args):
408 raise NotImplementedError
409
410 def remove_writer(self, fd):
411 raise NotImplementedError
412
413 # Completion based I/O methods returning Futures.
414
415 def sock_recv(self, sock, nbytes):
416 raise NotImplementedError
417
418 def sock_sendall(self, sock, data):
419 raise NotImplementedError
420
421 def sock_connect(self, sock, address):
422 raise NotImplementedError
423
424 def sock_accept(self, sock):
425 raise NotImplementedError
426
427 # Signal handling.
428
429 def add_signal_handler(self, sig, callback, *args):
430 raise NotImplementedError
431
432 def remove_signal_handler(self, sig):
433 raise NotImplementedError
434
Yury Selivanov569efa22014-02-18 18:02:19 -0500435 # Error handlers.
436
437 def set_exception_handler(self, handler):
438 raise NotImplementedError
439
440 def default_exception_handler(self, context):
441 raise NotImplementedError
442
443 def call_exception_handler(self, context):
444 raise NotImplementedError
445
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100446 # Debug flag management.
447
448 def get_debug(self):
449 raise NotImplementedError
450
451 def set_debug(self, enabled):
452 raise NotImplementedError
453
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700454
455class AbstractEventLoopPolicy:
456 """Abstract policy for accessing the event loop."""
457
458 def get_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200459 """Get the event loop for the current context.
460
461 Returns an event loop object implementing the BaseEventLoop interface,
462 or raises an exception in case no event loop has been set for the
463 current context and the current policy does not specify to create one.
464
465 It should never return None."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700466 raise NotImplementedError
467
468 def set_event_loop(self, loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200469 """Set the event loop for the current context to loop."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700470 raise NotImplementedError
471
472 def new_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200473 """Create and return a new event loop object according to this
474 policy's rules. If there's need to set this loop as the event loop for
475 the current context, set_event_loop must be called explicitly."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700476 raise NotImplementedError
477
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800478 # Child processes handling (Unix only).
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700479
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800480 def get_child_watcher(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200481 "Get the watcher for child processes."
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800482 raise NotImplementedError
483
484 def set_child_watcher(self, watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200485 """Set the watcher for child processes."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800486 raise NotImplementedError
487
488
489class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700490 """Default policy implementation for accessing the event loop.
491
492 In this policy, each thread has its own event loop. However, we
493 only automatically create an event loop by default for the main
494 thread; other threads by default have no event loop.
495
496 Other policies may have different rules (e.g. a single global
497 event loop, or automatically creating an event loop per thread, or
498 using some other notion of context to which an event loop is
499 associated).
500 """
501
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800502 _loop_factory = None
503
504 class _Local(threading.local):
505 _loop = None
506 _set_called = False
507
508 def __init__(self):
509 self._local = self._Local()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700510
511 def get_event_loop(self):
512 """Get the event loop.
513
514 This may be None or an instance of EventLoop.
515 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800516 if (self._local._loop is None and
517 not self._local._set_called and
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700518 isinstance(threading.current_thread(), threading._MainThread)):
Guido van Rossumcced0762013-11-27 10:37:13 -0800519 self.set_event_loop(self.new_event_loop())
Victor Stinner3a1c7382014-12-18 01:20:10 +0100520 if self._local._loop is None:
521 raise RuntimeError('There is no current event loop in thread %r.'
522 % threading.current_thread().name)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800523 return self._local._loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700524
525 def set_event_loop(self, loop):
526 """Set the event loop."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800527 self._local._set_called = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700528 assert loop is None or isinstance(loop, AbstractEventLoop)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800529 self._local._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700530
531 def new_event_loop(self):
532 """Create a new event loop.
533
534 You must call set_event_loop() to make this the current event
535 loop.
536 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800537 return self._loop_factory()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700538
539
540# Event loop policy. The policy itself is always global, even if the
541# policy's rules say that there is an event loop per thread (or other
542# notion of context). The default policy is installed by the first
543# call to get_event_loop_policy().
544_event_loop_policy = None
545
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800546# Lock for protecting the on-the-fly creation of the event loop policy.
547_lock = threading.Lock()
548
549
550def _init_event_loop_policy():
551 global _event_loop_policy
552 with _lock:
553 if _event_loop_policy is None: # pragma: no branch
554 from . import DefaultEventLoopPolicy
555 _event_loop_policy = DefaultEventLoopPolicy()
556
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700557
558def get_event_loop_policy():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200559 """Get the current event loop policy."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700560 if _event_loop_policy is None:
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800561 _init_event_loop_policy()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700562 return _event_loop_policy
563
564
565def set_event_loop_policy(policy):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200566 """Set the current event loop policy.
567
568 If policy is None, the default policy is restored."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700569 global _event_loop_policy
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700570 assert policy is None or isinstance(policy, AbstractEventLoopPolicy)
571 _event_loop_policy = policy
572
573
574def get_event_loop():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200575 """Equivalent to calling get_event_loop_policy().get_event_loop()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700576 return get_event_loop_policy().get_event_loop()
577
578
579def set_event_loop(loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200580 """Equivalent to calling get_event_loop_policy().set_event_loop(loop)."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700581 get_event_loop_policy().set_event_loop(loop)
582
583
584def new_event_loop():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200585 """Equivalent to calling get_event_loop_policy().new_event_loop()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700586 return get_event_loop_policy().new_event_loop()
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800587
588
589def get_child_watcher():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200590 """Equivalent to calling get_event_loop_policy().get_child_watcher()."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800591 return get_event_loop_policy().get_child_watcher()
592
593
594def set_child_watcher(watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200595 """Equivalent to calling
596 get_event_loop_policy().set_child_watcher(watcher)."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800597 return get_event_loop_policy().set_child_watcher(watcher)