blob: 3a33646df8f435d59bf5a469dcd90784fdabd6ce [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
Yury Selivanov45dccda2016-09-15 15:58:15 -040038def _format_args_and_kwargs(args, kwargs):
39 """Format function arguments and keyword arguments.
Victor Stinner313a9802014-07-29 12:58:23 +020040
41 Special case for a single parameter: ('hello',) is formatted as ('hello').
42 """
43 # use reprlib to limit the length of the output
Yury Selivanov45dccda2016-09-15 15:58:15 -040044 items = []
45 if args:
46 items.extend(reprlib.repr(arg) for arg in args)
47 if kwargs:
48 items.extend('{}={}'.format(k, reprlib.repr(v))
49 for k, v in kwargs.items())
50 return '(' + ', '.join(items) + ')'
Victor Stinner975735f2014-06-25 21:41:58 +020051
52
Yury Selivanov45dccda2016-09-15 15:58:15 -040053def _format_callback(func, args, kwargs, suffix=''):
Victor Stinner975735f2014-06-25 21:41:58 +020054 if isinstance(func, functools.partial):
Yury Selivanov45dccda2016-09-15 15:58:15 -040055 suffix = _format_args_and_kwargs(args, kwargs) + suffix
56 return _format_callback(func.func, func.args, func.keywords, suffix)
Victor Stinner975735f2014-06-25 21:41:58 +020057
Guido van Rossum0a9933e2015-05-02 18:38:24 -070058 if hasattr(func, '__qualname__'):
59 func_repr = getattr(func, '__qualname__')
60 elif hasattr(func, '__name__'):
61 func_repr = getattr(func, '__name__')
62 else:
Victor Stinner975735f2014-06-25 21:41:58 +020063 func_repr = repr(func)
64
Yury Selivanov45dccda2016-09-15 15:58:15 -040065 func_repr += _format_args_and_kwargs(args, kwargs)
Victor Stinner975735f2014-06-25 21:41:58 +020066 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):
Yury Selivanov45dccda2016-09-15 15:58:15 -040071 func_repr = _format_callback(func, args, None)
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
Yury Selivanovf6d991d2016-09-15 13:10:51 -0400252 def shutdown_asyncgens(self):
253 """Shutdown all active asynchronous generators."""
254 raise NotImplementedError
255
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700256 # Methods scheduling callbacks. All these return Handles.
257
Yury Selivanov592ada92014-09-25 12:07:56 -0400258 def _timer_handle_cancelled(self, handle):
259 """Notification that a TimerHandle has been cancelled."""
260 raise NotImplementedError
261
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700262 def call_soon(self, callback, *args):
263 return self.call_later(0, callback, *args)
264
265 def call_later(self, delay, callback, *args):
266 raise NotImplementedError
267
268 def call_at(self, when, callback, *args):
269 raise NotImplementedError
270
271 def time(self):
272 raise NotImplementedError
273
Yury Selivanov7661db62016-05-16 15:38:39 -0400274 def create_future(self):
275 raise NotImplementedError
276
Victor Stinner896a25a2014-07-08 11:29:25 +0200277 # Method scheduling a coroutine object: create a task.
278
279 def create_task(self, coro):
280 raise NotImplementedError
281
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700282 # Methods for interacting with threads.
283
284 def call_soon_threadsafe(self, callback, *args):
285 raise NotImplementedError
286
Yury Selivanov740169c2015-05-11 14:23:38 -0400287 def run_in_executor(self, executor, func, *args):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700288 raise NotImplementedError
289
290 def set_default_executor(self, executor):
291 raise NotImplementedError
292
293 # Network I/O methods returning Futures.
294
295 def getaddrinfo(self, host, port, *, family=0, type=0, proto=0, flags=0):
296 raise NotImplementedError
297
298 def getnameinfo(self, sockaddr, flags=0):
299 raise NotImplementedError
300
301 def create_connection(self, protocol_factory, host=None, port=None, *,
302 ssl=None, family=0, proto=0, flags=0, sock=None,
Guido van Rossum21c85a72013-11-01 14:16:54 -0700303 local_addr=None, server_hostname=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700304 raise NotImplementedError
305
306 def create_server(self, protocol_factory, host=None, port=None, *,
307 family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE,
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700308 sock=None, backlog=100, ssl=None, reuse_address=None,
309 reuse_port=None):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700310 """A coroutine which creates a TCP server bound to host and port.
311
312 The return value is a Server object which can be used to stop
313 the service.
314
315 If host is an empty string or None all interfaces are assumed
316 and a list of multiple sockets will be returned (most likely
Victor Stinner5e4a7d82015-09-21 18:33:43 +0200317 one for IPv4 and another one for IPv6). The host parameter can also be a
318 sequence (e.g. list) of hosts to bind to.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700319
320 family can be set to either AF_INET or AF_INET6 to force the
321 socket to use IPv4 or IPv6. If not set it will be determined
322 from host (defaults to AF_UNSPEC).
323
324 flags is a bitmask for getaddrinfo().
325
326 sock can optionally be specified in order to use a preexisting
327 socket object.
328
329 backlog is the maximum number of queued connections passed to
330 listen() (defaults to 100).
331
332 ssl can be set to an SSLContext to enable SSL over the
333 accepted connections.
334
335 reuse_address tells the kernel to reuse a local socket in
336 TIME_WAIT state, without waiting for its natural timeout to
337 expire. If not specified will automatically be set to True on
338 UNIX.
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700339
340 reuse_port tells the kernel to allow this endpoint to be bound to
341 the same port as other existing endpoints are bound to, so long as
342 they all set this flag when being created. This option is not
343 supported on Windows.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700344 """
345 raise NotImplementedError
346
Yury Selivanovb057c522014-02-18 12:15:06 -0500347 def create_unix_connection(self, protocol_factory, path, *,
348 ssl=None, sock=None,
349 server_hostname=None):
350 raise NotImplementedError
351
352 def create_unix_server(self, protocol_factory, path, *,
353 sock=None, backlog=100, ssl=None):
354 """A coroutine which creates a UNIX Domain Socket server.
355
Yury Selivanovdec1a452014-02-18 22:27:48 -0500356 The return value is a Server object, which can be used to stop
Yury Selivanovb057c522014-02-18 12:15:06 -0500357 the service.
358
359 path is a str, representing a file systsem path to bind the
360 server socket to.
361
362 sock can optionally be specified in order to use a preexisting
363 socket object.
364
365 backlog is the maximum number of queued connections passed to
366 listen() (defaults to 100).
367
368 ssl can be set to an SSLContext to enable SSL over the
369 accepted connections.
370 """
371 raise NotImplementedError
372
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700373 def create_datagram_endpoint(self, protocol_factory,
374 local_addr=None, remote_addr=None, *,
Guido van Rossumb9bf9132015-10-05 09:15:28 -0700375 family=0, proto=0, flags=0,
376 reuse_address=None, reuse_port=None,
377 allow_broadcast=None, sock=None):
378 """A coroutine which creates a datagram endpoint.
379
380 This method will try to establish the endpoint in the background.
381 When successful, the coroutine returns a (transport, protocol) pair.
382
383 protocol_factory must be a callable returning a protocol instance.
384
385 socket family AF_INET or socket.AF_INET6 depending on host (or
386 family if specified), socket type SOCK_DGRAM.
387
388 reuse_address tells the kernel to reuse a local socket in
389 TIME_WAIT state, without waiting for its natural timeout to
390 expire. If not specified it will automatically be set to True on
391 UNIX.
392
393 reuse_port tells the kernel to allow this endpoint to be bound to
394 the same port as other existing endpoints are bound to, so long as
395 they all set this flag when being created. This option is not
396 supported on Windows and some UNIX's. If the
397 :py:data:`~socket.SO_REUSEPORT` constant is not defined then this
398 capability is unsupported.
399
400 allow_broadcast tells the kernel to allow this endpoint to send
401 messages to the broadcast address.
402
403 sock can optionally be specified in order to use a preexisting
404 socket object.
405 """
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700406 raise NotImplementedError
407
Guido van Rossume3f52ef2013-11-01 14:19:04 -0700408 # Pipes and subprocesses.
409
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700410 def connect_read_pipe(self, protocol_factory, pipe):
Victor Stinnera5b257a2014-05-29 00:14:03 +0200411 """Register read pipe in event loop. Set the pipe to non-blocking mode.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700412
413 protocol_factory should instantiate object with Protocol interface.
Victor Stinnera5b257a2014-05-29 00:14:03 +0200414 pipe is a file-like object.
415 Return pair (transport, protocol), where transport supports the
Guido van Rossum9204af42013-11-30 15:35:42 -0800416 ReadTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700417 # The reason to accept file-like object instead of just file descriptor
418 # is: we need to own pipe and close it at transport finishing
419 # Can got complicated errors if pass f.fileno(),
420 # close fd in pipe transport then close f and vise versa.
421 raise NotImplementedError
422
423 def connect_write_pipe(self, protocol_factory, pipe):
Yury Selivanovdec1a452014-02-18 22:27:48 -0500424 """Register write pipe in event loop.
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700425
426 protocol_factory should instantiate object with BaseProtocol interface.
427 Pipe is file-like object already switched to nonblocking.
428 Return pair (transport, protocol), where transport support
Guido van Rossum9204af42013-11-30 15:35:42 -0800429 WriteTransport interface."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700430 # The reason to accept file-like object instead of just file descriptor
431 # is: we need to own pipe and close it at transport finishing
432 # Can got complicated errors if pass f.fileno(),
433 # close fd in pipe transport then close f and vise versa.
434 raise NotImplementedError
435
436 def subprocess_shell(self, protocol_factory, cmd, *, stdin=subprocess.PIPE,
437 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
438 **kwargs):
439 raise NotImplementedError
440
441 def subprocess_exec(self, protocol_factory, *args, stdin=subprocess.PIPE,
442 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
443 **kwargs):
444 raise NotImplementedError
445
446 # Ready-based callback registration methods.
447 # The add_*() methods return None.
448 # The remove_*() methods return True if something was removed,
449 # False if there was nothing to delete.
450
451 def add_reader(self, fd, callback, *args):
452 raise NotImplementedError
453
454 def remove_reader(self, fd):
455 raise NotImplementedError
456
457 def add_writer(self, fd, callback, *args):
458 raise NotImplementedError
459
460 def remove_writer(self, fd):
461 raise NotImplementedError
462
463 # Completion based I/O methods returning Futures.
464
465 def sock_recv(self, sock, nbytes):
466 raise NotImplementedError
467
468 def sock_sendall(self, sock, data):
469 raise NotImplementedError
470
471 def sock_connect(self, sock, address):
472 raise NotImplementedError
473
474 def sock_accept(self, sock):
475 raise NotImplementedError
476
477 # Signal handling.
478
479 def add_signal_handler(self, sig, callback, *args):
480 raise NotImplementedError
481
482 def remove_signal_handler(self, sig):
483 raise NotImplementedError
484
Yury Selivanov740169c2015-05-11 14:23:38 -0400485 # Task factory.
486
487 def set_task_factory(self, factory):
488 raise NotImplementedError
489
490 def get_task_factory(self):
491 raise NotImplementedError
492
Yury Selivanov569efa22014-02-18 18:02:19 -0500493 # Error handlers.
494
Yury Selivanov7ed7ce62016-05-16 15:20:38 -0400495 def get_exception_handler(self):
496 raise NotImplementedError
497
Yury Selivanov569efa22014-02-18 18:02:19 -0500498 def set_exception_handler(self, handler):
499 raise NotImplementedError
500
501 def default_exception_handler(self, context):
502 raise NotImplementedError
503
504 def call_exception_handler(self, context):
505 raise NotImplementedError
506
Victor Stinner0f3e6bc2014-02-19 23:15:02 +0100507 # Debug flag management.
508
509 def get_debug(self):
510 raise NotImplementedError
511
512 def set_debug(self, enabled):
513 raise NotImplementedError
514
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700515
516class AbstractEventLoopPolicy:
517 """Abstract policy for accessing the event loop."""
518
519 def get_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200520 """Get the event loop for the current context.
521
522 Returns an event loop object implementing the BaseEventLoop interface,
523 or raises an exception in case no event loop has been set for the
524 current context and the current policy does not specify to create one.
525
526 It should never return None."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700527 raise NotImplementedError
528
529 def set_event_loop(self, loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200530 """Set the event loop for the current context to loop."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700531 raise NotImplementedError
532
533 def new_event_loop(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200534 """Create and return a new event loop object according to this
535 policy's rules. If there's need to set this loop as the event loop for
536 the current context, set_event_loop must be called explicitly."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700537 raise NotImplementedError
538
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800539 # Child processes handling (Unix only).
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700540
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800541 def get_child_watcher(self):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200542 "Get the watcher for child processes."
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800543 raise NotImplementedError
544
545 def set_child_watcher(self, watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200546 """Set the watcher for child processes."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800547 raise NotImplementedError
548
549
550class BaseDefaultEventLoopPolicy(AbstractEventLoopPolicy):
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700551 """Default policy implementation for accessing the event loop.
552
553 In this policy, each thread has its own event loop. However, we
554 only automatically create an event loop by default for the main
555 thread; other threads by default have no event loop.
556
557 Other policies may have different rules (e.g. a single global
558 event loop, or automatically creating an event loop per thread, or
559 using some other notion of context to which an event loop is
560 associated).
561 """
562
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800563 _loop_factory = None
564
565 class _Local(threading.local):
566 _loop = None
567 _set_called = False
568
569 def __init__(self):
570 self._local = self._Local()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700571
572 def get_event_loop(self):
573 """Get the event loop.
574
575 This may be None or an instance of EventLoop.
576 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800577 if (self._local._loop is None and
578 not self._local._set_called and
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700579 isinstance(threading.current_thread(), threading._MainThread)):
Guido van Rossumcced0762013-11-27 10:37:13 -0800580 self.set_event_loop(self.new_event_loop())
Victor Stinner3a1c7382014-12-18 01:20:10 +0100581 if self._local._loop is None:
582 raise RuntimeError('There is no current event loop in thread %r.'
583 % threading.current_thread().name)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800584 return self._local._loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700585
586 def set_event_loop(self, loop):
587 """Set the event loop."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800588 self._local._set_called = True
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700589 assert loop is None or isinstance(loop, AbstractEventLoop)
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800590 self._local._loop = loop
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700591
592 def new_event_loop(self):
593 """Create a new event loop.
594
595 You must call set_event_loop() to make this the current event
596 loop.
597 """
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800598 return self._loop_factory()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700599
600
601# Event loop policy. The policy itself is always global, even if the
602# policy's rules say that there is an event loop per thread (or other
603# notion of context). The default policy is installed by the first
604# call to get_event_loop_policy().
605_event_loop_policy = None
606
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800607# Lock for protecting the on-the-fly creation of the event loop policy.
608_lock = threading.Lock()
609
610
611def _init_event_loop_policy():
612 global _event_loop_policy
613 with _lock:
614 if _event_loop_policy is None: # pragma: no branch
615 from . import DefaultEventLoopPolicy
616 _event_loop_policy = DefaultEventLoopPolicy()
617
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700618
619def get_event_loop_policy():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200620 """Get the current event loop policy."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700621 if _event_loop_policy is None:
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800622 _init_event_loop_policy()
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700623 return _event_loop_policy
624
625
626def set_event_loop_policy(policy):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200627 """Set the current event loop policy.
628
629 If policy is None, the default policy is restored."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700630 global _event_loop_policy
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700631 assert policy is None or isinstance(policy, AbstractEventLoopPolicy)
632 _event_loop_policy = policy
633
634
635def get_event_loop():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200636 """Equivalent to calling get_event_loop_policy().get_event_loop()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700637 return get_event_loop_policy().get_event_loop()
638
639
640def set_event_loop(loop):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200641 """Equivalent to calling get_event_loop_policy().set_event_loop(loop)."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700642 get_event_loop_policy().set_event_loop(loop)
643
644
645def new_event_loop():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200646 """Equivalent to calling get_event_loop_policy().new_event_loop()."""
Guido van Rossum27b7c7e2013-10-17 13:40:50 -0700647 return get_event_loop_policy().new_event_loop()
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800648
649
650def get_child_watcher():
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200651 """Equivalent to calling get_event_loop_policy().get_child_watcher()."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800652 return get_event_loop_policy().get_child_watcher()
653
654
655def set_child_watcher(watcher):
Victor Stinnerf9e49dd2014-06-05 12:06:44 +0200656 """Equivalent to calling
657 get_event_loop_policy().set_child_watcher(watcher)."""
Guido van Rossum0eaa5ac2013-11-04 15:50:46 -0800658 return get_event_loop_policy().set_child_watcher(watcher)