blob: 496075bacf36465a35254ed8beca579c0d857c66 [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
Guido van Rossum0a9933e2015-05-02 18:38:24 -070057 if hasattr(func, '__qualname__'):
58 func_repr = getattr(func, '__qualname__')
59 elif hasattr(func, '__name__'):
60 func_repr = getattr(func, '__name__')
61 else:
Victor Stinner975735f2014-06-25 21:41:58 +020062 func_repr = repr(func)
63
64 if args is not None:
65 func_repr += _format_args(args)
66 if suffix:
67 func_repr += suffix
Guido van Rossum0a9933e2015-05-02 18:38:24 -070068 return func_repr
Victor Stinner975735f2014-06-25 21:41:58 +020069
Guido van Rossum0a9933e2015-05-02 18:38:24 -070070def _format_callback_source(func, args):
71 func_repr = _format_callback(func, args)
Victor Stinner975735f2014-06-25 21:41:58 +020072 source = _get_function_source(func)
73 if source:
74 func_repr += ' at %s:%s' % source
75 return func_repr
76
77
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070078class Handle:
79 """Object returned by callback registration methods."""
80
Victor Stinner80f53aa2014-06-27 13:52:20 +020081 __slots__ = ('_callback', '_args', '_cancelled', '_loop',
Victor Stinner1b38bc62014-09-17 23:24:13 +020082 '_source_traceback', '_repr', '__weakref__')
Yury Selivanovb1317782014-02-12 17:01:52 -050083
Yury Selivanov569efa22014-02-18 18:02:19 -050084 def __init__(self, callback, args, loop):
Victor Stinnerdc62b7e2014-02-10 00:45:44 +010085 assert not isinstance(callback, Handle), 'A Handle is not a callback'
Yury Selivanov569efa22014-02-18 18:02:19 -050086 self._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070087 self._callback = callback
88 self._args = args
89 self._cancelled = False
Victor Stinner1b38bc62014-09-17 23:24:13 +020090 self._repr = None
Victor Stinner80f53aa2014-06-27 13:52:20 +020091 if self._loop.get_debug():
92 self._source_traceback = traceback.extract_stack(sys._getframe(1))
93 else:
94 self._source_traceback = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070095
Victor Stinner1b38bc62014-09-17 23:24:13 +020096 def _repr_info(self):
Victor Stinnerf68bd882014-07-10 22:32:58 +020097 info = [self.__class__.__name__]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070098 if self._cancelled:
Victor Stinner975735f2014-06-25 21:41:58 +020099 info.append('cancelled')
Victor Stinnerf68bd882014-07-10 22:32:58 +0200100 if self._callback is not None:
Guido van Rossum0a9933e2015-05-02 18:38:24 -0700101 info.append(_format_callback_source(self._callback, self._args))
Victor Stinnerf68bd882014-07-10 22:32:58 +0200102 if self._source_traceback:
103 frame = self._source_traceback[-1]
104 info.append('created at %s:%s' % (frame[0], frame[1]))
Victor Stinner1b38bc62014-09-17 23:24:13 +0200105 return info
106
107 def __repr__(self):
108 if self._repr is not None:
109 return self._repr
110 info = self._repr_info()
Victor Stinnerf68bd882014-07-10 22:32:58 +0200111 return '<%s>' % ' '.join(info)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700112
113 def cancel(self):
Yury Selivanov592ada92014-09-25 12:07:56 -0400114 if not self._cancelled:
115 self._cancelled = True
116 if self._loop.get_debug():
117 # Keep a representation in debug mode to keep callback and
118 # parameters. For example, to log the warning
119 # "Executing <Handle...> took 2.5 second"
120 self._repr = repr(self)
121 self._callback = None
122 self._args = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700123
124 def _run(self):
125 try:
126 self._callback(*self._args)
Yury Selivanov569efa22014-02-18 18:02:19 -0500127 except Exception as exc:
Guido van Rossum0a9933e2015-05-02 18:38:24 -0700128 cb = _format_callback_source(self._callback, self._args)
Victor Stinner17b53f12014-06-26 01:35:45 +0200129 msg = 'Exception in callback {}'.format(cb)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200130 context = {
Yury Selivanov569efa22014-02-18 18:02:19 -0500131 'message': msg,
132 'exception': exc,
133 'handle': self,
Victor Stinner80f53aa2014-06-27 13:52:20 +0200134 }
135 if self._source_traceback:
136 context['source_traceback'] = self._source_traceback
137 self._loop.call_exception_handler(context)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700138 self = None # Needed to break cycles when an exception occurs.
139
140
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700141class TimerHandle(Handle):
142 """Object returned by timed callback registration methods."""
143
Yury Selivanov592ada92014-09-25 12:07:56 -0400144 __slots__ = ['_scheduled', '_when']
Yury Selivanovb1317782014-02-12 17:01:52 -0500145
Yury Selivanov569efa22014-02-18 18:02:19 -0500146 def __init__(self, when, callback, args, loop):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700147 assert when is not None
Yury Selivanov569efa22014-02-18 18:02:19 -0500148 super().__init__(callback, args, loop)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200149 if self._source_traceback:
150 del self._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700151 self._when = when
Yury Selivanov592ada92014-09-25 12:07:56 -0400152 self._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700153
Victor Stinner1b38bc62014-09-17 23:24:13 +0200154 def _repr_info(self):
155 info = super()._repr_info()
156 pos = 2 if self._cancelled else 1
157 info.insert(pos, 'when=%s' % self._when)
158 return info
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700159
160 def __hash__(self):
161 return hash(self._when)
162
163 def __lt__(self, other):
164 return self._when < other._when
165
166 def __le__(self, other):
167 if self._when < other._when:
168 return True
169 return self.__eq__(other)
170
171 def __gt__(self, other):
172 return self._when > other._when
173
174 def __ge__(self, other):
175 if self._when > other._when:
176 return True
177 return self.__eq__(other)
178
179 def __eq__(self, other):
180 if isinstance(other, TimerHandle):
181 return (self._when == other._when and
182 self._callback == other._callback and
183 self._args == other._args and
184 self._cancelled == other._cancelled)
185 return NotImplemented
186
187 def __ne__(self, other):
188 equal = self.__eq__(other)
189 return NotImplemented if equal is NotImplemented else not equal
190
Yury Selivanov592ada92014-09-25 12:07:56 -0400191 def cancel(self):
192 if not self._cancelled:
193 self._loop._timer_handle_cancelled(self)
194 super().cancel()
195
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700196
197class AbstractServer:
Victor Stinnercf6f72e2013-12-03 18:23:52 +0100198 """Abstract server returned by create_server()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700199
200 def close(self):
201 """Stop serving. This leaves existing connections open."""
202 return NotImplemented
203
204 def wait_closed(self):
205 """Coroutine to wait until service is closed."""
206 return NotImplemented
207
208
209class AbstractEventLoop:
210 """Abstract event loop."""
211
212 # Running and stopping the event loop.
213
214 def run_forever(self):
215 """Run the event loop until stop() is called."""
216 raise NotImplementedError
217
218 def run_until_complete(self, future):
219 """Run the event loop until a Future is done.
220
221 Return the Future's result, or raise its exception.
222 """
223 raise NotImplementedError
224
225 def stop(self):
226 """Stop the event loop as soon as reasonable.
227
228 Exactly how soon that is may depend on the implementation, but
229 no more I/O callbacks should be scheduled.
230 """
231 raise NotImplementedError
232
233 def is_running(self):
234 """Return whether the event loop is currently running."""
235 raise NotImplementedError
236
Victor Stinner896a25a2014-07-08 11:29:25 +0200237 def is_closed(self):
238 """Returns True if the event loop was closed."""
239 raise NotImplementedError
240
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700241 def close(self):
242 """Close the loop.
243
244 The loop should not be running.
245
246 This is idempotent and irreversible.
247
248 No other methods should be called after this one.
249 """
250 raise NotImplementedError
251
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700252 # Methods scheduling callbacks. All these return Handles.
253
Yury Selivanov592ada92014-09-25 12:07:56 -0400254 def _timer_handle_cancelled(self, handle):
255 """Notification that a TimerHandle has been cancelled."""
256 raise NotImplementedError
257
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700258 def call_soon(self, callback, *args):
259 return self.call_later(0, callback, *args)
260
261 def call_later(self, delay, callback, *args):
262 raise NotImplementedError
263
264 def call_at(self, when, callback, *args):
265 raise NotImplementedError
266
267 def time(self):
268 raise NotImplementedError
269
Victor Stinner896a25a2014-07-08 11:29:25 +0200270 # Method scheduling a coroutine object: create a task.
271
272 def create_task(self, coro):
273 raise NotImplementedError
274
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700275 # Methods for interacting with threads.
276
277 def call_soon_threadsafe(self, callback, *args):
278 raise NotImplementedError
279
Yury Selivanov740169c2015-05-11 14:23:38 -0400280 def run_in_executor(self, executor, func, *args):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700281 raise NotImplementedError
282
283 def set_default_executor(self, executor):
284 raise NotImplementedError
285
286 # Network I/O methods returning Futures.
287
288 def getaddrinfo(self, host, port, *, family=0, type=0, proto=0, flags=0):
289 raise NotImplementedError
290
291 def getnameinfo(self, sockaddr, flags=0):
292 raise NotImplementedError
293
294 def create_connection(self, protocol_factory, host=None, port=None, *,
295 ssl=None, family=0, proto=0, flags=0, sock=None,
Guido van Rossum21c85a72013-11-01 14:16:54 -0700296 local_addr=None, server_hostname=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700297 raise NotImplementedError
298
299 def create_server(self, protocol_factory, host=None, port=None, *,
300 family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE,
301 sock=None, backlog=100, ssl=None, reuse_address=None):
302 """A coroutine which creates a TCP server bound to host and port.
303
304 The return value is a Server object which can be used to stop
305 the service.
306
307 If host is an empty string or None all interfaces are assumed
308 and a list of multiple sockets will be returned (most likely
309 one for IPv4 and another one for IPv6).
310
311 family can be set to either AF_INET or AF_INET6 to force the
312 socket to use IPv4 or IPv6. If not set it will be determined
313 from host (defaults to AF_UNSPEC).
314
315 flags is a bitmask for getaddrinfo().
316
317 sock can optionally be specified in order to use a preexisting
318 socket object.
319
320 backlog is the maximum number of queued connections passed to
321 listen() (defaults to 100).
322
323 ssl can be set to an SSLContext to enable SSL over the
324 accepted connections.
325
326 reuse_address tells the kernel to reuse a local socket in
327 TIME_WAIT state, without waiting for its natural timeout to
328 expire. If not specified will automatically be set to True on
329 UNIX.
330 """
331 raise NotImplementedError
332
Yury Selivanovb057c522014-02-18 12:15:06 -0500333 def create_unix_connection(self, protocol_factory, path, *,
334 ssl=None, sock=None,
335 server_hostname=None):
336 raise NotImplementedError
337
338 def create_unix_server(self, protocol_factory, path, *,
339 sock=None, backlog=100, ssl=None):
340 """A coroutine which creates a UNIX Domain Socket server.
341
Yury Selivanovdec1a452014-02-18 22:27:48 -0500342 The return value is a Server object, which can be used to stop
Yury Selivanovb057c522014-02-18 12:15:06 -0500343 the service.
344
345 path is a str, representing a file systsem path to bind the
346 server socket to.
347
348 sock can optionally be specified in order to use a preexisting
349 socket object.
350
351 backlog is the maximum number of queued connections passed to
352 listen() (defaults to 100).
353
354 ssl can be set to an SSLContext to enable SSL over the
355 accepted connections.
356 """
357 raise NotImplementedError
358
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700359 def create_datagram_endpoint(self, protocol_factory,
360 local_addr=None, remote_addr=None, *,
361 family=0, proto=0, flags=0):
362 raise NotImplementedError
363
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700364 # Pipes and subprocesses.
365
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700366 def connect_read_pipe(self, protocol_factory, pipe):
Victor Stinnera5b257a2014-05-29 00:14:03 +0200367 """Register read pipe in event loop. Set the pipe to non-blocking mode.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700368
369 protocol_factory should instantiate object with Protocol interface.
Victor Stinnera5b257a2014-05-29 00:14:03 +0200370 pipe is a file-like object.
371 Return pair (transport, protocol), where transport supports the
Guido van Rossum9204af42013-11-30 15:35:42 -0800372 ReadTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700373 # The reason to accept file-like object instead of just file descriptor
374 # is: we need to own pipe and close it at transport finishing
375 # Can got complicated errors if pass f.fileno(),
376 # close fd in pipe transport then close f and vise versa.
377 raise NotImplementedError
378
379 def connect_write_pipe(self, protocol_factory, pipe):
Yury Selivanovdec1a452014-02-18 22:27:48 -0500380 """Register write pipe in event loop.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700381
382 protocol_factory should instantiate object with BaseProtocol interface.
383 Pipe is file-like object already switched to nonblocking.
384 Return pair (transport, protocol), where transport support
Guido van Rossum9204af42013-11-30 15:35:42 -0800385 WriteTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700386 # The reason to accept file-like object instead of just file descriptor
387 # is: we need to own pipe and close it at transport finishing
388 # Can got complicated errors if pass f.fileno(),
389 # close fd in pipe transport then close f and vise versa.
390 raise NotImplementedError
391
392 def subprocess_shell(self, protocol_factory, cmd, *, stdin=subprocess.PIPE,
393 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
394 **kwargs):
395 raise NotImplementedError
396
397 def subprocess_exec(self, protocol_factory, *args, stdin=subprocess.PIPE,
398 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
399 **kwargs):
400 raise NotImplementedError
401
402 # Ready-based callback registration methods.
403 # The add_*() methods return None.
404 # The remove_*() methods return True if something was removed,
405 # False if there was nothing to delete.
406
407 def add_reader(self, fd, callback, *args):
408 raise NotImplementedError
409
410 def remove_reader(self, fd):
411 raise NotImplementedError
412
413 def add_writer(self, fd, callback, *args):
414 raise NotImplementedError
415
416 def remove_writer(self, fd):
417 raise NotImplementedError
418
419 # Completion based I/O methods returning Futures.
420
421 def sock_recv(self, sock, nbytes):
422 raise NotImplementedError
423
424 def sock_sendall(self, sock, data):
425 raise NotImplementedError
426
427 def sock_connect(self, sock, address):
428 raise NotImplementedError
429
430 def sock_accept(self, sock):
431 raise NotImplementedError
432
433 # Signal handling.
434
435 def add_signal_handler(self, sig, callback, *args):
436 raise NotImplementedError
437
438 def remove_signal_handler(self, sig):
439 raise NotImplementedError
440
Yury Selivanov740169c2015-05-11 14:23:38 -0400441 # Task factory.
442
443 def set_task_factory(self, factory):
444 raise NotImplementedError
445
446 def get_task_factory(self):
447 raise NotImplementedError
448
Yury Selivanov569efa22014-02-18 18:02:19 -0500449 # Error handlers.
450
451 def set_exception_handler(self, handler):
452 raise NotImplementedError
453
454 def default_exception_handler(self, context):
455 raise NotImplementedError
456
457 def call_exception_handler(self, context):
458 raise NotImplementedError
459
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100460 # Debug flag management.
461
462 def get_debug(self):
463 raise NotImplementedError
464
465 def set_debug(self, enabled):
466 raise NotImplementedError
467
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700468
469class AbstractEventLoopPolicy:
470 """Abstract policy for accessing the event loop."""
471
472 def get_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200473 """Get the event loop for the current context.
474
475 Returns an event loop object implementing the BaseEventLoop interface,
476 or raises an exception in case no event loop has been set for the
477 current context and the current policy does not specify to create one.
478
479 It should never return None."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700480 raise NotImplementedError
481
482 def set_event_loop(self, loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200483 """Set the event loop for the current context to loop."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700484 raise NotImplementedError
485
486 def new_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200487 """Create and return a new event loop object according to this
488 policy's rules. If there's need to set this loop as the event loop for
489 the current context, set_event_loop must be called explicitly."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700490 raise NotImplementedError
491
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800492 # Child processes handling (Unix only).
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700493
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800494 def get_child_watcher(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200495 "Get the watcher for child processes."
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800496 raise NotImplementedError
497
498 def set_child_watcher(self, watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200499 """Set the watcher for child processes."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800500 raise NotImplementedError
501
502
503class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700504 """Default policy implementation for accessing the event loop.
505
506 In this policy, each thread has its own event loop. However, we
507 only automatically create an event loop by default for the main
508 thread; other threads by default have no event loop.
509
510 Other policies may have different rules (e.g. a single global
511 event loop, or automatically creating an event loop per thread, or
512 using some other notion of context to which an event loop is
513 associated).
514 """
515
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800516 _loop_factory = None
517
518 class _Local(threading.local):
519 _loop = None
520 _set_called = False
521
522 def __init__(self):
523 self._local = self._Local()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700524
525 def get_event_loop(self):
526 """Get the event loop.
527
528 This may be None or an instance of EventLoop.
529 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800530 if (self._local._loop is None and
531 not self._local._set_called and
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700532 isinstance(threading.current_thread(), threading._MainThread)):
Guido van Rossumcced0762013-11-27 10:37:13 -0800533 self.set_event_loop(self.new_event_loop())
Victor Stinner3a1c7382014-12-18 01:20:10 +0100534 if self._local._loop is None:
535 raise RuntimeError('There is no current event loop in thread %r.'
536 % threading.current_thread().name)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800537 return self._local._loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700538
539 def set_event_loop(self, loop):
540 """Set the event loop."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800541 self._local._set_called = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700542 assert loop is None or isinstance(loop, AbstractEventLoop)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800543 self._local._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700544
545 def new_event_loop(self):
546 """Create a new event loop.
547
548 You must call set_event_loop() to make this the current event
549 loop.
550 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800551 return self._loop_factory()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700552
553
554# Event loop policy. The policy itself is always global, even if the
555# policy's rules say that there is an event loop per thread (or other
556# notion of context). The default policy is installed by the first
557# call to get_event_loop_policy().
558_event_loop_policy = None
559
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800560# Lock for protecting the on-the-fly creation of the event loop policy.
561_lock = threading.Lock()
562
563
564def _init_event_loop_policy():
565 global _event_loop_policy
566 with _lock:
567 if _event_loop_policy is None: # pragma: no branch
568 from . import DefaultEventLoopPolicy
569 _event_loop_policy = DefaultEventLoopPolicy()
570
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700571
572def get_event_loop_policy():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200573 """Get the current event loop policy."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700574 if _event_loop_policy is None:
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800575 _init_event_loop_policy()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700576 return _event_loop_policy
577
578
579def set_event_loop_policy(policy):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200580 """Set the current event loop policy.
581
582 If policy is None, the default policy is restored."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700583 global _event_loop_policy
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700584 assert policy is None or isinstance(policy, AbstractEventLoopPolicy)
585 _event_loop_policy = policy
586
587
588def get_event_loop():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200589 """Equivalent to calling get_event_loop_policy().get_event_loop()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700590 return get_event_loop_policy().get_event_loop()
591
592
593def set_event_loop(loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200594 """Equivalent to calling get_event_loop_policy().set_event_loop(loop)."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700595 get_event_loop_policy().set_event_loop(loop)
596
597
598def new_event_loop():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200599 """Equivalent to calling get_event_loop_policy().new_event_loop()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700600 return get_event_loop_policy().new_event_loop()
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800601
602
603def get_child_watcher():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200604 """Equivalent to calling get_event_loop_policy().get_child_watcher()."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800605 return get_event_loop_policy().get_child_watcher()
606
607
608def set_child_watcher(watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200609 """Equivalent to calling
610 get_event_loop_policy().set_child_watcher(watcher)."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800611 return get_event_loop_policy().set_child_watcher(watcher)