diff options
author | Guido van Rossum <guido@python.org> | 2013-12-06 20:57:40 (GMT) |
---|---|---|
committer | Guido van Rossum <guido@python.org> | 2013-12-06 20:57:40 (GMT) |
commit | 1a605ed5a33dbeec6b98d2a073fbbe3fcfdd84c0 (patch) | |
tree | fce1163198c3e6f531b8cd0e03413f589ada61c0 /Lib/asyncio/tasks.py | |
parent | 2f8c83568ca5850601e92e315c4a1c840e94b1cb (diff) | |
download | cpython-1a605ed5a33dbeec6b98d2a073fbbe3fcfdd84c0.zip cpython-1a605ed5a33dbeec6b98d2a073fbbe3fcfdd84c0.tar.gz cpython-1a605ed5a33dbeec6b98d2a073fbbe3fcfdd84c0.tar.bz2 |
asyncio: Add Task.current_task() class method.
Diffstat (limited to 'Lib/asyncio/tasks.py')
-rw-r--r-- | Lib/asyncio/tasks.py | 20 |
1 files changed, 20 insertions, 0 deletions
diff --git a/Lib/asyncio/tasks.py b/Lib/asyncio/tasks.py index 999e962..cd9718f 100644 --- a/Lib/asyncio/tasks.py +++ b/Lib/asyncio/tasks.py @@ -122,6 +122,22 @@ class Task(futures.Future): # Weak set containing all tasks alive. _all_tasks = weakref.WeakSet() + # Dictionary containing tasks that are currently active in + # all running event loops. {EventLoop: Task} + _current_tasks = {} + + @classmethod + def current_task(cls, loop=None): + """Return the currently running task in an event loop or None. + + By default the current task for the current event loop is returned. + + None is returned when called not in the context of a Task. + """ + if loop is None: + loop = events.get_event_loop() + return cls._current_tasks.get(loop) + @classmethod def all_tasks(cls, loop=None): """Return a set of all tasks for an event loop. @@ -252,6 +268,8 @@ class Task(futures.Future): self._must_cancel = False coro = self._coro self._fut_waiter = None + + self.__class__._current_tasks[self._loop] = self # Call either coro.throw(exc) or coro.send(value). try: if exc is not None: @@ -302,6 +320,8 @@ class Task(futures.Future): self._step, None, RuntimeError( 'Task got bad yield: {!r}'.format(result))) + finally: + self.__class__._current_tasks.pop(self._loop) self = None def _wakeup(self, future): |