blob: 176a846698448d31f8c9a921707c7d1d0db2b7cd [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
Victor Stinner71080fc2015-07-25 02:23:21 +020020from asyncio import compat
Victor Stinner307bccc2014-06-12 18:39:26 +020021
Victor Stinner975735f2014-06-25 21:41:58 +020022
Victor Stinner307bccc2014-06-12 18:39:26 +020023def _get_function_source(func):
Victor Stinner71080fc2015-07-25 02:23:21 +020024 if compat.PY34:
Victor Stinner307bccc2014-06-12 18:39:26 +020025 func = inspect.unwrap(func)
26 elif hasattr(func, '__wrapped__'):
27 func = func.__wrapped__
28 if inspect.isfunction(func):
29 code = func.__code__
30 return (code.co_filename, code.co_firstlineno)
31 if isinstance(func, functools.partial):
32 return _get_function_source(func.func)
Victor Stinner71080fc2015-07-25 02:23:21 +020033 if compat.PY34 and isinstance(func, functools.partialmethod):
Victor Stinner307bccc2014-06-12 18:39:26 +020034 return _get_function_source(func.func)
35 return None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070036
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070037
Victor Stinner975735f2014-06-25 21:41:58 +020038def _format_args(args):
Victor Stinner313a9802014-07-29 12:58:23 +020039 """Format function arguments.
40
41 Special case for a single parameter: ('hello',) is formatted as ('hello').
42 """
43 # use reprlib to limit the length of the output
44 args_repr = reprlib.repr(args)
Victor Stinner975735f2014-06-25 21:41:58 +020045 if len(args) == 1 and args_repr.endswith(',)'):
46 args_repr = args_repr[:-2] + ')'
47 return args_repr
48
49
50def _format_callback(func, args, suffix=''):
51 if isinstance(func, functools.partial):
52 if args is not None:
53 suffix = _format_args(args) + suffix
54 return _format_callback(func.func, func.args, suffix)
55
Guido van Rossum0a9933e2015-05-02 18:38:24 -070056 if hasattr(func, '__qualname__'):
57 func_repr = getattr(func, '__qualname__')
58 elif hasattr(func, '__name__'):
59 func_repr = getattr(func, '__name__')
60 else:
Victor Stinner975735f2014-06-25 21:41:58 +020061 func_repr = repr(func)
62
63 if args is not None:
64 func_repr += _format_args(args)
65 if suffix:
66 func_repr += suffix
Guido van Rossum0a9933e2015-05-02 18:38:24 -070067 return func_repr
Victor Stinner975735f2014-06-25 21:41:58 +020068
Guido van Rossum0a9933e2015-05-02 18:38:24 -070069def _format_callback_source(func, args):
70 func_repr = _format_callback(func, args)
Victor Stinner975735f2014-06-25 21:41:58 +020071 source = _get_function_source(func)
72 if source:
73 func_repr += ' at %s:%s' % source
74 return func_repr
75
76
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070077class Handle:
78 """Object returned by callback registration methods."""
79
Victor Stinner80f53aa2014-06-27 13:52:20 +020080 __slots__ = ('_callback', '_args', '_cancelled', '_loop',
Victor Stinner1b38bc62014-09-17 23:24:13 +020081 '_source_traceback', '_repr', '__weakref__')
Yury Selivanovb1317782014-02-12 17:01:52 -050082
Yury Selivanov569efa22014-02-18 18:02:19 -050083 def __init__(self, callback, args, loop):
Victor Stinnerdc62b7e2014-02-10 00:45:44 +010084 assert not isinstance(callback, Handle), 'A Handle is not a callback'
Yury Selivanov569efa22014-02-18 18:02:19 -050085 self._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070086 self._callback = callback
87 self._args = args
88 self._cancelled = False
Victor Stinner1b38bc62014-09-17 23:24:13 +020089 self._repr = None
Victor Stinner80f53aa2014-06-27 13:52:20 +020090 if self._loop.get_debug():
91 self._source_traceback = traceback.extract_stack(sys._getframe(1))
92 else:
93 self._source_traceback = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070094
Victor Stinner1b38bc62014-09-17 23:24:13 +020095 def _repr_info(self):
Victor Stinnerf68bd882014-07-10 22:32:58 +020096 info = [self.__class__.__name__]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -070097 if self._cancelled:
Victor Stinner975735f2014-06-25 21:41:58 +020098 info.append('cancelled')
Victor Stinnerf68bd882014-07-10 22:32:58 +020099 if self._callback is not None:
Guido van Rossum0a9933e2015-05-02 18:38:24 -0700100 info.append(_format_callback_source(self._callback, self._args))
Victor Stinnerf68bd882014-07-10 22:32:58 +0200101 if self._source_traceback:
102 frame = self._source_traceback[-1]
103 info.append('created at %s:%s' % (frame[0], frame[1]))
Victor Stinner1b38bc62014-09-17 23:24:13 +0200104 return info
105
106 def __repr__(self):
107 if self._repr is not None:
108 return self._repr
109 info = self._repr_info()
Victor Stinnerf68bd882014-07-10 22:32:58 +0200110 return '<%s>' % ' '.join(info)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700111
112 def cancel(self):
Yury Selivanov592ada92014-09-25 12:07:56 -0400113 if not self._cancelled:
114 self._cancelled = True
115 if self._loop.get_debug():
116 # Keep a representation in debug mode to keep callback and
117 # parameters. For example, to log the warning
118 # "Executing <Handle...> took 2.5 second"
119 self._repr = repr(self)
120 self._callback = None
121 self._args = None
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700122
123 def _run(self):
124 try:
125 self._callback(*self._args)
Yury Selivanov569efa22014-02-18 18:02:19 -0500126 except Exception as exc:
Guido van Rossum0a9933e2015-05-02 18:38:24 -0700127 cb = _format_callback_source(self._callback, self._args)
Victor Stinner17b53f12014-06-26 01:35:45 +0200128 msg = 'Exception in callback {}'.format(cb)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200129 context = {
Yury Selivanov569efa22014-02-18 18:02:19 -0500130 'message': msg,
131 'exception': exc,
132 'handle': self,
Victor Stinner80f53aa2014-06-27 13:52:20 +0200133 }
134 if self._source_traceback:
135 context['source_traceback'] = self._source_traceback
136 self._loop.call_exception_handler(context)
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700137 self = None # Needed to break cycles when an exception occurs.
138
139
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700140class TimerHandle(Handle):
141 """Object returned by timed callback registration methods."""
142
Yury Selivanov592ada92014-09-25 12:07:56 -0400143 __slots__ = ['_scheduled', '_when']
Yury Selivanovb1317782014-02-12 17:01:52 -0500144
Yury Selivanov569efa22014-02-18 18:02:19 -0500145 def __init__(self, when, callback, args, loop):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700146 assert when is not None
Yury Selivanov569efa22014-02-18 18:02:19 -0500147 super().__init__(callback, args, loop)
Victor Stinner80f53aa2014-06-27 13:52:20 +0200148 if self._source_traceback:
149 del self._source_traceback[-1]
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700150 self._when = when
Yury Selivanov592ada92014-09-25 12:07:56 -0400151 self._scheduled = False
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700152
Victor Stinner1b38bc62014-09-17 23:24:13 +0200153 def _repr_info(self):
154 info = super()._repr_info()
155 pos = 2 if self._cancelled else 1
156 info.insert(pos, 'when=%s' % self._when)
157 return info
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700158
159 def __hash__(self):
160 return hash(self._when)
161
162 def __lt__(self, other):
163 return self._when < other._when
164
165 def __le__(self, other):
166 if self._when < other._when:
167 return True
168 return self.__eq__(other)
169
170 def __gt__(self, other):
171 return self._when > other._when
172
173 def __ge__(self, other):
174 if self._when > other._when:
175 return True
176 return self.__eq__(other)
177
178 def __eq__(self, other):
179 if isinstance(other, TimerHandle):
180 return (self._when == other._when and
181 self._callback == other._callback and
182 self._args == other._args and
183 self._cancelled == other._cancelled)
184 return NotImplemented
185
186 def __ne__(self, other):
187 equal = self.__eq__(other)
188 return NotImplemented if equal is NotImplemented else not equal
189
Yury Selivanov592ada92014-09-25 12:07:56 -0400190 def cancel(self):
191 if not self._cancelled:
192 self._loop._timer_handle_cancelled(self)
193 super().cancel()
194
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700195
196class AbstractServer:
Victor Stinnercf6f72e2013-12-03 18:23:52 +0100197 """Abstract server returned by create_server()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700198
199 def close(self):
200 """Stop serving. This leaves existing connections open."""
201 return NotImplemented
202
203 def wait_closed(self):
204 """Coroutine to wait until service is closed."""
205 return NotImplemented
206
207
208class AbstractEventLoop:
209 """Abstract event loop."""
210
211 # Running and stopping the event loop.
212
213 def run_forever(self):
214 """Run the event loop until stop() is called."""
215 raise NotImplementedError
216
217 def run_until_complete(self, future):
218 """Run the event loop until a Future is done.
219
220 Return the Future's result, or raise its exception.
221 """
222 raise NotImplementedError
223
224 def stop(self):
225 """Stop the event loop as soon as reasonable.
226
227 Exactly how soon that is may depend on the implementation, but
228 no more I/O callbacks should be scheduled.
229 """
230 raise NotImplementedError
231
232 def is_running(self):
233 """Return whether the event loop is currently running."""
234 raise NotImplementedError
235
Victor Stinner896a25a2014-07-08 11:29:25 +0200236 def is_closed(self):
237 """Returns True if the event loop was closed."""
238 raise NotImplementedError
239
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700240 def close(self):
241 """Close the loop.
242
243 The loop should not be running.
244
245 This is idempotent and irreversible.
246
247 No other methods should be called after this one.
248 """
249 raise NotImplementedError
250
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700251 # Methods scheduling callbacks. All these return Handles.
252
Yury Selivanov592ada92014-09-25 12:07:56 -0400253 def _timer_handle_cancelled(self, handle):
254 """Notification that a TimerHandle has been cancelled."""
255 raise NotImplementedError
256
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700257 def call_soon(self, callback, *args):
258 return self.call_later(0, callback, *args)
259
260 def call_later(self, delay, callback, *args):
261 raise NotImplementedError
262
263 def call_at(self, when, callback, *args):
264 raise NotImplementedError
265
266 def time(self):
267 raise NotImplementedError
268
Victor Stinner896a25a2014-07-08 11:29:25 +0200269 # Method scheduling a coroutine object: create a task.
270
271 def create_task(self, coro):
272 raise NotImplementedError
273
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700274 # Methods for interacting with threads.
275
276 def call_soon_threadsafe(self, callback, *args):
277 raise NotImplementedError
278
Yury Selivanov740169c2015-05-11 14:23:38 -0400279 def run_in_executor(self, executor, func, *args):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700280 raise NotImplementedError
281
282 def set_default_executor(self, executor):
283 raise NotImplementedError
284
285 # Network I/O methods returning Futures.
286
287 def getaddrinfo(self, host, port, *, family=0, type=0, proto=0, flags=0):
288 raise NotImplementedError
289
290 def getnameinfo(self, sockaddr, flags=0):
291 raise NotImplementedError
292
293 def create_connection(self, protocol_factory, host=None, port=None, *,
294 ssl=None, family=0, proto=0, flags=0, sock=None,
Guido van Rossum21c85a72013-11-01 14:16:54 -0700295 local_addr=None, server_hostname=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700296 raise NotImplementedError
297
298 def create_server(self, protocol_factory, host=None, port=None, *,
299 family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE,
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700300 sock=None, backlog=100, ssl=None, reuse_address=None,
301 reuse_port=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700302 """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
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200309 one for IPv4 and another one for IPv6). The host parameter can also be a
310 sequence (e.g. list) of hosts to bind to.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700311
312 family can be set to either AF_INET or AF_INET6 to force the
313 socket to use IPv4 or IPv6. If not set it will be determined
314 from host (defaults to AF_UNSPEC).
315
316 flags is a bitmask for getaddrinfo().
317
318 sock can optionally be specified in order to use a preexisting
319 socket object.
320
321 backlog is the maximum number of queued connections passed to
322 listen() (defaults to 100).
323
324 ssl can be set to an SSLContext to enable SSL over the
325 accepted connections.
326
327 reuse_address tells the kernel to reuse a local socket in
328 TIME_WAIT state, without waiting for its natural timeout to
329 expire. If not specified will automatically be set to True on
330 UNIX.
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700331
332 reuse_port tells the kernel to allow this endpoint to be bound to
333 the same port as other existing endpoints are bound to, so long as
334 they all set this flag when being created. This option is not
335 supported on Windows.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700336 """
337 raise NotImplementedError
338
Yury Selivanovb057c522014-02-18 12:15:06 -0500339 def create_unix_connection(self, protocol_factory, path, *,
340 ssl=None, sock=None,
341 server_hostname=None):
342 raise NotImplementedError
343
344 def create_unix_server(self, protocol_factory, path, *,
345 sock=None, backlog=100, ssl=None):
346 """A coroutine which creates a UNIX Domain Socket server.
347
Yury Selivanovdec1a452014-02-18 22:27:48 -0500348 The return value is a Server object, which can be used to stop
Yury Selivanovb057c522014-02-18 12:15:06 -0500349 the service.
350
351 path is a str, representing a file systsem path to bind the
352 server socket to.
353
354 sock can optionally be specified in order to use a preexisting
355 socket object.
356
357 backlog is the maximum number of queued connections passed to
358 listen() (defaults to 100).
359
360 ssl can be set to an SSLContext to enable SSL over the
361 accepted connections.
362 """
363 raise NotImplementedError
364
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700365 def create_datagram_endpoint(self, protocol_factory,
366 local_addr=None, remote_addr=None, *,
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700367 family=0, proto=0, flags=0,
368 reuse_address=None, reuse_port=None,
369 allow_broadcast=None, sock=None):
370 """A coroutine which creates a datagram endpoint.
371
372 This method will try to establish the endpoint in the background.
373 When successful, the coroutine returns a (transport, protocol) pair.
374
375 protocol_factory must be a callable returning a protocol instance.
376
377 socket family AF_INET or socket.AF_INET6 depending on host (or
378 family if specified), socket type SOCK_DGRAM.
379
380 reuse_address tells the kernel to reuse a local socket in
381 TIME_WAIT state, without waiting for its natural timeout to
382 expire. If not specified it will automatically be set to True on
383 UNIX.
384
385 reuse_port tells the kernel to allow this endpoint to be bound to
386 the same port as other existing endpoints are bound to, so long as
387 they all set this flag when being created. This option is not
388 supported on Windows and some UNIX's. If the
389 :py:data:`~socket.SO_REUSEPORT` constant is not defined then this
390 capability is unsupported.
391
392 allow_broadcast tells the kernel to allow this endpoint to send
393 messages to the broadcast address.
394
395 sock can optionally be specified in order to use a preexisting
396 socket object.
397 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700398 raise NotImplementedError
399
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700400 # Pipes and subprocesses.
401
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700402 def connect_read_pipe(self, protocol_factory, pipe):
Victor Stinnera5b257a2014-05-29 00:14:03 +0200403 """Register read pipe in event loop. Set the pipe to non-blocking mode.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700404
405 protocol_factory should instantiate object with Protocol interface.
Victor Stinnera5b257a2014-05-29 00:14:03 +0200406 pipe is a file-like object.
407 Return pair (transport, protocol), where transport supports the
Guido van Rossum9204af42013-11-30 15:35:42 -0800408 ReadTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700409 # The reason to accept file-like object instead of just file descriptor
410 # is: we need to own pipe and close it at transport finishing
411 # Can got complicated errors if pass f.fileno(),
412 # close fd in pipe transport then close f and vise versa.
413 raise NotImplementedError
414
415 def connect_write_pipe(self, protocol_factory, pipe):
Yury Selivanovdec1a452014-02-18 22:27:48 -0500416 """Register write pipe in event loop.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700417
418 protocol_factory should instantiate object with BaseProtocol interface.
419 Pipe is file-like object already switched to nonblocking.
420 Return pair (transport, protocol), where transport support
Guido van Rossum9204af42013-11-30 15:35:42 -0800421 WriteTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700422 # The reason to accept file-like object instead of just file descriptor
423 # is: we need to own pipe and close it at transport finishing
424 # Can got complicated errors if pass f.fileno(),
425 # close fd in pipe transport then close f and vise versa.
426 raise NotImplementedError
427
428 def subprocess_shell(self, protocol_factory, cmd, *, stdin=subprocess.PIPE,
429 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
430 **kwargs):
431 raise NotImplementedError
432
433 def subprocess_exec(self, protocol_factory, *args, stdin=subprocess.PIPE,
434 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
435 **kwargs):
436 raise NotImplementedError
437
438 # Ready-based callback registration methods.
439 # The add_*() methods return None.
440 # The remove_*() methods return True if something was removed,
441 # False if there was nothing to delete.
442
443 def add_reader(self, fd, callback, *args):
444 raise NotImplementedError
445
446 def remove_reader(self, fd):
447 raise NotImplementedError
448
449 def add_writer(self, fd, callback, *args):
450 raise NotImplementedError
451
452 def remove_writer(self, fd):
453 raise NotImplementedError
454
455 # Completion based I/O methods returning Futures.
456
457 def sock_recv(self, sock, nbytes):
458 raise NotImplementedError
459
460 def sock_sendall(self, sock, data):
461 raise NotImplementedError
462
463 def sock_connect(self, sock, address):
464 raise NotImplementedError
465
466 def sock_accept(self, sock):
467 raise NotImplementedError
468
469 # Signal handling.
470
471 def add_signal_handler(self, sig, callback, *args):
472 raise NotImplementedError
473
474 def remove_signal_handler(self, sig):
475 raise NotImplementedError
476
Yury Selivanov740169c2015-05-11 14:23:38 -0400477 # Task factory.
478
479 def set_task_factory(self, factory):
480 raise NotImplementedError
481
482 def get_task_factory(self):
483 raise NotImplementedError
484
Yury Selivanov569efa22014-02-18 18:02:19 -0500485 # Error handlers.
486
487 def set_exception_handler(self, handler):
488 raise NotImplementedError
489
490 def default_exception_handler(self, context):
491 raise NotImplementedError
492
493 def call_exception_handler(self, context):
494 raise NotImplementedError
495
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100496 # Debug flag management.
497
498 def get_debug(self):
499 raise NotImplementedError
500
501 def set_debug(self, enabled):
502 raise NotImplementedError
503
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700504
505class AbstractEventLoopPolicy:
506 """Abstract policy for accessing the event loop."""
507
508 def get_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200509 """Get the event loop for the current context.
510
511 Returns an event loop object implementing the BaseEventLoop interface,
512 or raises an exception in case no event loop has been set for the
513 current context and the current policy does not specify to create one.
514
515 It should never return None."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700516 raise NotImplementedError
517
518 def set_event_loop(self, loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200519 """Set the event loop for the current context to loop."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700520 raise NotImplementedError
521
522 def new_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200523 """Create and return a new event loop object according to this
524 policy's rules. If there's need to set this loop as the event loop for
525 the current context, set_event_loop must be called explicitly."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700526 raise NotImplementedError
527
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800528 # Child processes handling (Unix only).
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700529
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800530 def get_child_watcher(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200531 "Get the watcher for child processes."
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800532 raise NotImplementedError
533
534 def set_child_watcher(self, watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200535 """Set the watcher for child processes."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800536 raise NotImplementedError
537
538
539class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700540 """Default policy implementation for accessing the event loop.
541
542 In this policy, each thread has its own event loop. However, we
543 only automatically create an event loop by default for the main
544 thread; other threads by default have no event loop.
545
546 Other policies may have different rules (e.g. a single global
547 event loop, or automatically creating an event loop per thread, or
548 using some other notion of context to which an event loop is
549 associated).
550 """
551
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800552 _loop_factory = None
553
554 class _Local(threading.local):
555 _loop = None
556 _set_called = False
557
558 def __init__(self):
559 self._local = self._Local()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700560
561 def get_event_loop(self):
562 """Get the event loop.
563
564 This may be None or an instance of EventLoop.
565 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800566 if (self._local._loop is None and
567 not self._local._set_called and
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700568 isinstance(threading.current_thread(), threading._MainThread)):
Guido van Rossumcced0762013-11-27 10:37:13 -0800569 self.set_event_loop(self.new_event_loop())
Victor Stinner3a1c7382014-12-18 01:20:10 +0100570 if self._local._loop is None:
571 raise RuntimeError('There is no current event loop in thread %r.'
572 % threading.current_thread().name)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800573 return self._local._loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700574
575 def set_event_loop(self, loop):
576 """Set the event loop."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800577 self._local._set_called = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700578 assert loop is None or isinstance(loop, AbstractEventLoop)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800579 self._local._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700580
581 def new_event_loop(self):
582 """Create a new event loop.
583
584 You must call set_event_loop() to make this the current event
585 loop.
586 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800587 return self._loop_factory()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700588
589
590# Event loop policy. The policy itself is always global, even if the
591# policy's rules say that there is an event loop per thread (or other
592# notion of context). The default policy is installed by the first
593# call to get_event_loop_policy().
594_event_loop_policy = None
595
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800596# Lock for protecting the on-the-fly creation of the event loop policy.
597_lock = threading.Lock()
598
599
600def _init_event_loop_policy():
601 global _event_loop_policy
602 with _lock:
603 if _event_loop_policy is None: # pragma: no branch
604 from . import DefaultEventLoopPolicy
605 _event_loop_policy = DefaultEventLoopPolicy()
606
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700607
608def get_event_loop_policy():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200609 """Get the current event loop policy."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700610 if _event_loop_policy is None:
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800611 _init_event_loop_policy()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700612 return _event_loop_policy
613
614
615def set_event_loop_policy(policy):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200616 """Set the current event loop policy.
617
618 If policy is None, the default policy is restored."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700619 global _event_loop_policy
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700620 assert policy is None or isinstance(policy, AbstractEventLoopPolicy)
621 _event_loop_policy = policy
622
623
624def get_event_loop():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200625 """Equivalent to calling get_event_loop_policy().get_event_loop()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700626 return get_event_loop_policy().get_event_loop()
627
628
629def set_event_loop(loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200630 """Equivalent to calling get_event_loop_policy().set_event_loop(loop)."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700631 get_event_loop_policy().set_event_loop(loop)
632
633
634def new_event_loop():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200635 """Equivalent to calling get_event_loop_policy().new_event_loop()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700636 return get_event_loop_policy().new_event_loop()
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800637
638
639def get_child_watcher():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200640 """Equivalent to calling get_event_loop_policy().get_child_watcher()."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800641 return get_event_loop_policy().get_child_watcher()
642
643
644def set_child_watcher(watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200645 """Equivalent to calling
646 get_event_loop_policy().set_child_watcher(watcher)."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800647 return get_event_loop_policy().set_child_watcher(watcher)