blob: 01320cdf62bf2e2af1ec098fb57cead77318097b [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
Yury Selivanov592ada92014-09-25 12:07:56 -0400181 def cancel(self):
182 if not self._cancelled:
183 self._loop._timer_handle_cancelled(self)
184 super().cancel()
185
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700186
187class AbstractServer:
Victor Stinnercf6f72e2013-12-03 18:23:52 +0100188 """Abstract server returned by create_server()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700189
190 def close(self):
191 """Stop serving. This leaves existing connections open."""
192 return NotImplemented
193
194 def wait_closed(self):
195 """Coroutine to wait until service is closed."""
196 return NotImplemented
197
198
199class AbstractEventLoop:
200 """Abstract event loop."""
201
202 # Running and stopping the event loop.
203
204 def run_forever(self):
205 """Run the event loop until stop() is called."""
206 raise NotImplementedError
207
208 def run_until_complete(self, future):
209 """Run the event loop until a Future is done.
210
211 Return the Future's result, or raise its exception.
212 """
213 raise NotImplementedError
214
215 def stop(self):
216 """Stop the event loop as soon as reasonable.
217
218 Exactly how soon that is may depend on the implementation, but
219 no more I/O callbacks should be scheduled.
220 """
221 raise NotImplementedError
222
223 def is_running(self):
224 """Return whether the event loop is currently running."""
225 raise NotImplementedError
226
Victor Stinner896a25a2014-07-08 11:29:25 +0200227 def is_closed(self):
228 """Returns True if the event loop was closed."""
229 raise NotImplementedError
230
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700231 def close(self):
232 """Close the loop.
233
234 The loop should not be running.
235
236 This is idempotent and irreversible.
237
238 No other methods should be called after this one.
239 """
240 raise NotImplementedError
241
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700242 # Methods scheduling callbacks. All these return Handles.
243
Yury Selivanov592ada92014-09-25 12:07:56 -0400244 def _timer_handle_cancelled(self, handle):
245 """Notification that a TimerHandle has been cancelled."""
246 raise NotImplementedError
247
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700248 def call_soon(self, callback, *args):
249 return self.call_later(0, callback, *args)
250
251 def call_later(self, delay, callback, *args):
252 raise NotImplementedError
253
254 def call_at(self, when, callback, *args):
255 raise NotImplementedError
256
257 def time(self):
258 raise NotImplementedError
259
Victor Stinner896a25a2014-07-08 11:29:25 +0200260 # Method scheduling a coroutine object: create a task.
261
262 def create_task(self, coro):
263 raise NotImplementedError
264
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700265 # Methods for interacting with threads.
266
267 def call_soon_threadsafe(self, callback, *args):
268 raise NotImplementedError
269
270 def run_in_executor(self, executor, callback, *args):
271 raise NotImplementedError
272
273 def set_default_executor(self, executor):
274 raise NotImplementedError
275
276 # Network I/O methods returning Futures.
277
278 def getaddrinfo(self, host, port, *, family=0, type=0, proto=0, flags=0):
279 raise NotImplementedError
280
281 def getnameinfo(self, sockaddr, flags=0):
282 raise NotImplementedError
283
284 def create_connection(self, protocol_factory, host=None, port=None, *,
285 ssl=None, family=0, proto=0, flags=0, sock=None,
Guido van Rossum21c85a72013-11-01 14:16:54 -0700286 local_addr=None, server_hostname=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700287 raise NotImplementedError
288
289 def create_server(self, protocol_factory, host=None, port=None, *,
290 family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE,
291 sock=None, backlog=100, ssl=None, reuse_address=None):
292 """A coroutine which creates a TCP server bound to host and port.
293
294 The return value is a Server object which can be used to stop
295 the service.
296
297 If host is an empty string or None all interfaces are assumed
298 and a list of multiple sockets will be returned (most likely
299 one for IPv4 and another one for IPv6).
300
301 family can be set to either AF_INET or AF_INET6 to force the
302 socket to use IPv4 or IPv6. If not set it will be determined
303 from host (defaults to AF_UNSPEC).
304
305 flags is a bitmask for getaddrinfo().
306
307 sock can optionally be specified in order to use a preexisting
308 socket object.
309
310 backlog is the maximum number of queued connections passed to
311 listen() (defaults to 100).
312
313 ssl can be set to an SSLContext to enable SSL over the
314 accepted connections.
315
316 reuse_address tells the kernel to reuse a local socket in
317 TIME_WAIT state, without waiting for its natural timeout to
318 expire. If not specified will automatically be set to True on
319 UNIX.
320 """
321 raise NotImplementedError
322
Yury Selivanovb057c522014-02-18 12:15:06 -0500323 def create_unix_connection(self, protocol_factory, path, *,
324 ssl=None, sock=None,
325 server_hostname=None):
326 raise NotImplementedError
327
328 def create_unix_server(self, protocol_factory, path, *,
329 sock=None, backlog=100, ssl=None):
330 """A coroutine which creates a UNIX Domain Socket server.
331
Yury Selivanovdec1a452014-02-18 22:27:48 -0500332 The return value is a Server object, which can be used to stop
Yury Selivanovb057c522014-02-18 12:15:06 -0500333 the service.
334
335 path is a str, representing a file systsem path to bind the
336 server socket to.
337
338 sock can optionally be specified in order to use a preexisting
339 socket object.
340
341 backlog is the maximum number of queued connections passed to
342 listen() (defaults to 100).
343
344 ssl can be set to an SSLContext to enable SSL over the
345 accepted connections.
346 """
347 raise NotImplementedError
348
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700349 def create_datagram_endpoint(self, protocol_factory,
350 local_addr=None, remote_addr=None, *,
351 family=0, proto=0, flags=0):
352 raise NotImplementedError
353
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700354 # Pipes and subprocesses.
355
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700356 def connect_read_pipe(self, protocol_factory, pipe):
Victor Stinnera5b257a2014-05-29 00:14:03 +0200357 """Register read pipe in event loop. Set the pipe to non-blocking mode.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700358
359 protocol_factory should instantiate object with Protocol interface.
Victor Stinnera5b257a2014-05-29 00:14:03 +0200360 pipe is a file-like object.
361 Return pair (transport, protocol), where transport supports the
Guido van Rossum9204af42013-11-30 15:35:42 -0800362 ReadTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700363 # The reason to accept file-like object instead of just file descriptor
364 # is: we need to own pipe and close it at transport finishing
365 # Can got complicated errors if pass f.fileno(),
366 # close fd in pipe transport then close f and vise versa.
367 raise NotImplementedError
368
369 def connect_write_pipe(self, protocol_factory, pipe):
Yury Selivanovdec1a452014-02-18 22:27:48 -0500370 """Register write pipe in event loop.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700371
372 protocol_factory should instantiate object with BaseProtocol interface.
373 Pipe is file-like object already switched to nonblocking.
374 Return pair (transport, protocol), where transport support
Guido van Rossum9204af42013-11-30 15:35:42 -0800375 WriteTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700376 # The reason to accept file-like object instead of just file descriptor
377 # is: we need to own pipe and close it at transport finishing
378 # Can got complicated errors if pass f.fileno(),
379 # close fd in pipe transport then close f and vise versa.
380 raise NotImplementedError
381
382 def subprocess_shell(self, protocol_factory, cmd, *, stdin=subprocess.PIPE,
383 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
384 **kwargs):
385 raise NotImplementedError
386
387 def subprocess_exec(self, protocol_factory, *args, stdin=subprocess.PIPE,
388 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
389 **kwargs):
390 raise NotImplementedError
391
392 # Ready-based callback registration methods.
393 # The add_*() methods return None.
394 # The remove_*() methods return True if something was removed,
395 # False if there was nothing to delete.
396
397 def add_reader(self, fd, callback, *args):
398 raise NotImplementedError
399
400 def remove_reader(self, fd):
401 raise NotImplementedError
402
403 def add_writer(self, fd, callback, *args):
404 raise NotImplementedError
405
406 def remove_writer(self, fd):
407 raise NotImplementedError
408
409 # Completion based I/O methods returning Futures.
410
411 def sock_recv(self, sock, nbytes):
412 raise NotImplementedError
413
414 def sock_sendall(self, sock, data):
415 raise NotImplementedError
416
417 def sock_connect(self, sock, address):
418 raise NotImplementedError
419
420 def sock_accept(self, sock):
421 raise NotImplementedError
422
423 # Signal handling.
424
425 def add_signal_handler(self, sig, callback, *args):
426 raise NotImplementedError
427
428 def remove_signal_handler(self, sig):
429 raise NotImplementedError
430
Yury Selivanov569efa22014-02-18 18:02:19 -0500431 # Error handlers.
432
433 def set_exception_handler(self, handler):
434 raise NotImplementedError
435
436 def default_exception_handler(self, context):
437 raise NotImplementedError
438
439 def call_exception_handler(self, context):
440 raise NotImplementedError
441
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100442 # Debug flag management.
443
444 def get_debug(self):
445 raise NotImplementedError
446
447 def set_debug(self, enabled):
448 raise NotImplementedError
449
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700450
451class AbstractEventLoopPolicy:
452 """Abstract policy for accessing the event loop."""
453
454 def get_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200455 """Get the event loop for the current context.
456
457 Returns an event loop object implementing the BaseEventLoop interface,
458 or raises an exception in case no event loop has been set for the
459 current context and the current policy does not specify to create one.
460
461 It should never return None."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700462 raise NotImplementedError
463
464 def set_event_loop(self, loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200465 """Set the event loop for the current context to loop."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700466 raise NotImplementedError
467
468 def new_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200469 """Create and return a new event loop object according to this
470 policy's rules. If there's need to set this loop as the event loop for
471 the current context, set_event_loop must be called explicitly."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700472 raise NotImplementedError
473
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800474 # Child processes handling (Unix only).
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700475
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800476 def get_child_watcher(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200477 "Get the watcher for child processes."
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800478 raise NotImplementedError
479
480 def set_child_watcher(self, watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200481 """Set the watcher for child processes."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800482 raise NotImplementedError
483
484
485class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700486 """Default policy implementation for accessing the event loop.
487
488 In this policy, each thread has its own event loop. However, we
489 only automatically create an event loop by default for the main
490 thread; other threads by default have no event loop.
491
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
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800498 _loop_factory = None
499
500 class _Local(threading.local):
501 _loop = None
502 _set_called = False
503
504 def __init__(self):
505 self._local = self._Local()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700506
507 def get_event_loop(self):
508 """Get the event loop.
509
510 This may be None or an instance of EventLoop.
511 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800512 if (self._local._loop is None and
513 not self._local._set_called and
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700514 isinstance(threading.current_thread(), threading._MainThread)):
Guido van Rossumcced0762013-11-27 10:37:13 -0800515 self.set_event_loop(self.new_event_loop())
Victor Stinner3a1c7382014-12-18 01:20:10 +0100516 if self._local._loop is None:
517 raise RuntimeError('There is no current event loop in thread %r.'
518 % threading.current_thread().name)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800519 return self._local._loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700520
521 def set_event_loop(self, loop):
522 """Set the event loop."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800523 self._local._set_called = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700524 assert loop is None or isinstance(loop, AbstractEventLoop)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800525 self._local._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700526
527 def new_event_loop(self):
528 """Create a new event loop.
529
530 You must call set_event_loop() to make this the current event
531 loop.
532 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800533 return self._loop_factory()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700534
535
536# Event loop policy. The policy itself is always global, even if the
537# policy's rules say that there is an event loop per thread (or other
538# notion of context). The default policy is installed by the first
539# call to get_event_loop_policy().
540_event_loop_policy = None
541
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800542# Lock for protecting the on-the-fly creation of the event loop policy.
543_lock = threading.Lock()
544
545
546def _init_event_loop_policy():
547 global _event_loop_policy
548 with _lock:
549 if _event_loop_policy is None: # pragma: no branch
550 from . import DefaultEventLoopPolicy
551 _event_loop_policy = DefaultEventLoopPolicy()
552
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700553
554def get_event_loop_policy():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200555 """Get the current event loop policy."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700556 if _event_loop_policy is None:
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800557 _init_event_loop_policy()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700558 return _event_loop_policy
559
560
561def set_event_loop_policy(policy):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200562 """Set the current event loop policy.
563
564 If policy is None, the default policy is restored."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700565 global _event_loop_policy
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700566 assert policy is None or isinstance(policy, AbstractEventLoopPolicy)
567 _event_loop_policy = policy
568
569
570def get_event_loop():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200571 """Equivalent to calling get_event_loop_policy().get_event_loop()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700572 return get_event_loop_policy().get_event_loop()
573
574
575def set_event_loop(loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200576 """Equivalent to calling get_event_loop_policy().set_event_loop(loop)."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700577 get_event_loop_policy().set_event_loop(loop)
578
579
580def new_event_loop():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200581 """Equivalent to calling get_event_loop_policy().new_event_loop()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700582 return get_event_loop_policy().new_event_loop()
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800583
584
585def get_child_watcher():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200586 """Equivalent to calling get_event_loop_policy().get_child_watcher()."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800587 return get_event_loop_policy().get_child_watcher()
588
589
590def set_child_watcher(watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200591 """Equivalent to calling
592 get_event_loop_policy().set_child_watcher(watcher)."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800593 return get_event_loop_policy().set_child_watcher(watcher)