Skip to content

Added the create_task() method to TaskGroup - #1098

Merged
agronholm merged 36 commits into
masterfrom
improved-task-group
Apr 14, 2026
Merged

agronholm merged 36 commits into
masterfrom
improved-task-group

Conversation

@agronholm

@agronholm agronholm commented Mar 25, 2026 •

Copy link
Copy Markdown
Owner

NOTE Erasing or replacing the contents of this template will result in your pull
request being summarily closed without consideration!

Changes

This adds a mostly asyncio-compatible create_task() method to the TaskGroup class.
Like its asyncio counterpart, this method accepts a coroutine object and returns an awaitable task handle.

Checklist

If this is a user-facing code change, like a bugfix or a new feature, please ensure that
you've fulfilled the following conditions (where applicable):

  • You've added tests (in tests/) which would fail without your patch
  • You've updated the documentation (in docs/), in case of behavior changes or new
    features
  • You've added a new changelog entry (in docs/versionhistory.rst).

If this is a trivial change, like a typo fix or a code reformatting, then you can ignore
these instructions.

Updating the changelog

If there are no entries after the last release, use **UNRELEASED** as the version.
If, say, your patch fixes issue #123, the entry should look like this:

- Fix big bad boo-boo in task groups
  (`#123 <https://github.com/agronholm/anyio/issues/123>`_; PR by @yourgithubaccount)

If there's no issue linked, just link to your pull request instead by updating the
changelog after you've created the PR.

Comment thread src/anyio/_core/_tasks.py Resolved

@tapetersen tapetersen left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks fine to me and while a lot of code I've written has benefitted from rewriting to communicat return values through other means sometimes a single handle for cancelling and getting a return value vs. a cancel-scope and a memory-channel/event+var is really all that's needed and deserves a simple construct.

Comment thread src/anyio/_core/_tasks.py Resolved
Comment thread src/anyio/_core/_tasks.py

if self._exception is not None:
raise self._exception

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since these handles now are "leaked" to user code they can be awaited multiple times. Raising the same exception instance will modify the shared-instance's stack-trace (which is what I understand the reason why Outcome has dissallowed unwrapping more than once and now tries to change the api to copy the exception before raising).

I'm quite sure the futures in vanilla asyncio has the same issue so status quo may very well be acceptable, especially if this is intended to be a straight alternative, and we can assume users already need to be aware.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is precisely the code I had in that try...except block which I removed. I'm unsure which way to go here.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As the current behavior is consistent with asyncio I would say it's completely acceptable to leave it as is.

Copying is arguably more correct but I'm really not sure if it's generally safe and how expensive it is given that the vast majority of cases will definitely be the case of it being awaited exactly once.

Purity wise you could even argue that you shoulnd't throw the exception from the task to an outside waiter at all (what if it's a leaked StopIteration ...) and instead wrap it in a TaskErrored like the aborted/cancelled cases with the caller responsible for unwrapping it but I would definitely say that's too far.

I would probably lean towards the best choice being keeping it as it is now unless the copying costs a lot less than I think even if I myself tend to prefer api's doing it the "correct but slower" way. I'm completely fine with either.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Exception copying is not generally safe. What's on the table is disallowing users from waiting on the same task handle twice, but I'm not sure if such a thing is warranted in the first place.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What's on the table is disallowing users from waiting on the same task handle twice, but I'm not sure if such a thing is warranted in the first place.

Would it be reasonable to disallow this for now and reconsider supporting it later if a compelling use-case comes up? If we support it now and want to disallow it later, it would be backwards incompatible.

@gschaffner gschaffner Mar 28, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I am uneasy about exposing the property TaskHandle.exception. raise task_handle.exception seems like a footgun that is too easy to shoot oneself with; it has the same issues that Tobias brought up in this thread.

What is the motivation for exposing TaskHandle.exception publicly?

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the motivation for exposing TaskHandle.exception publicly?

Parity with asyncio.Task.

@agronholm agronholm Mar 29, 2026 •

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is a huge number of ways people could shoot their foot, and surprisingly many will go the great lengths to find such ways. If I removed the exception property, rest assured some enterprising coder would find the _exception attribute and use that to re-raise the exception.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

While I do agree (somewhat) with your motivation here, it's quite unfortunate that sub-optimal asyncio design decisions that somewhat-worked a decade ago now force us to replicate these misteaks.

On the plus side, we can always replace that exception attribute with a property that issues a deprecation warning and tells people to please call reraise() instead (or whichever other reasonable interface we can think of).

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What mistakes are you seeing here? And no, I'm not going slap a deprecation on the exception attribute. It's useful for introspection and monitoring tools. Otherwise you'll have to await on the handle and get the exception re-raised, and even then you'd have to dig it up from __cause__. Is that what you want?

Comment thread src/anyio/_core/_tasks.py Resolved
@agronholm

Copy link
Copy Markdown
Owner Author

How do you feel about the repr() output? I made it closely resemble the repr() of an asyncio Task object.

Comment thread src/anyio/_core/_tasks.py Resolved
@m-u-xyz

m-u-xyz commented Mar 27, 2026

Copy link
Copy Markdown
Collaborator

tg.create_task(taskfunc())

We intentionally don't do that anywhere else in the anyio code base.

I'm mostly-OK with supporting a coroutine-based task creation method for more convenient migration (though I'd never use it), but what I'm not really OK with is a TaskHandle that's only available via asyncio's IMHO-broken calling conventions.

@agronholm

Copy link
Copy Markdown
Owner Author

I agree that create_task() shouldn't swallow exceptions. Even asyncio.TaskGroup would raise an exception group here. But at the same time we can't hold on to the principle of awaiting only once since the exception goes to the task group first.

@tapetersen

tapetersen commented Mar 27, 2026 •

Copy link
Copy Markdown
Collaborator

I agree that create_task() shouldn't swallow exceptions. Even asyncio.TaskGroup would raise an exception group here. But at the same time we can't hold on to the principle of awaiting only once since the exception goes to the task group first.

With that problem as well as the context linking when raising I'm actually really starting to get convinced, always wrapping exceptions is the better idea and worth a bit clunkier code when trying to catch and handle specific exceptions (you would need an except and a match/isinstance check).

@agronholm

Copy link
Copy Markdown
Owner Author

I agree that create_task() shouldn't swallow exceptions. Even asyncio.TaskGroup would raise an exception group here. But at the same time we can't hold on to the principle of awaiting only once since the exception goes to the task group first.

With that problem as well as the context linking when 'm actually really starting to get convinced always wrapping exceptions is the better idea and worth a bit clunkier code when trying to catch and handle specific exceptions (you would need an except and a match/is instance check).

I'm already on it :) I'll push some changes Soon (tm).

@agronholm

Copy link
Copy Markdown
Owner Author

Done, and I like this design better already.

@agronholm

Copy link
Copy Markdown
Owner Author

Feel free to bikeshed on the exception and enum names. Now would be a good time for that.

Comment thread src/anyio/_core/_exceptions.py Resolved
@agronholm

Copy link
Copy Markdown
Owner Author

OK, so where do we stand on the design now? Right now the implementation raises the exceptions directly from the task group, but if the handle is waited on, the exception is wrapped so as not to pollute the original __context__.

@gschaffner

gschaffner commented Mar 28, 2026 •

Copy link
Copy Markdown
Collaborator

I agree that create_task() shouldn't swallow exceptions. Even asyncio.TaskGroup would raise an exception group here. But at the same time we can't hold on to the principle of awaiting only once since the exception goes to the task group first.

I don't think that that would prevent us from implementing "exactly once" exception semantics. Here is a quick-and-dirty sketch of an implementation: cef88f6...b6729cc

OK, so where do we stand on the design now? Right now the implementation raises the exceptions directly from the task group, but if the handle is waited on, the exception is wrapped so as not to pollute the original __context__.

An observation: this breaks the symmetry between TaskGroup.create_task and BlockingPortal.start_task_soon. Not to imply that that's necessarily a problem—just something to note/consider.

Overall the new "never move an exception" exception semantics seem good to me. I think that the "can move an exception"/"exactly once" exception semantics would be more flexible and would enable more use cases. However, on balance, the "never-move" semantics are IMO likely the better decision here if the primary objective of this API is to make it easier for asyncio.TaskGroup.create_task users (and to a lesser extent, asyncio.create_task users) to switch to AnyIO.

Analysis that motivated ^ (click to expand)

Different options for TaskGroup.create_task semantics will affect users differently. Comparing the following two options that have been proposed:

  • An Exception from a create_task task is never moved to the task's TaskHandle waiter, but instead the waiter will wake up with raise TaskError. An Exception from a create_task task immediately cancels the task group. Call this "never-move"/"can-cancel" semantics.

  • A create_task task can have its Exception moved to its TaskHandle waiter, but if it isn't moved then the exception will still be raised exactly once. An Exception from a create_task task does not cancel the task group. Call this "can-move"/"never-cancel" semantics.

Both of these options prevent the user from accidentally suppressing an exception.

The two different options will place different restrictions on the use cases for TaskGroup.create_task. Here is my current thinking:

  • "Can-move" semantics (but not "never-move" semantics) allow the user to use a TaskGroup to capture a function's result. I.e. if the user awaits the handle (and even if the handle wait gets cancelled), then create_task behaves like this:

    T = TypeVar("T")
    P = ParamSpec("P")
    BaseExceptionT = TypeVar("BaseExceptionT", bound=BaseException)
    
    
    @dataclass(frozen=True, slots=True)
    class Result(Generic[T]):
        value: T
    
        def unwrap(self) -> T:
            return self.value
    
    
    @dataclass(frozen=True, slots=True)
    class Error(Generic[BaseExceptionT]):
        exception: BaseExceptionT
    
        def unwrap(self) -> Never:
            context = self.exception.__context__
            try:
                # Preserve __cause__ and __suppress_context__ by avoiding `raise ...
                # from ...`
                raise self.exception
            finally:
                # Preserve __context__. TODO: Consider doing: If there is a second context
                # at the call site that is awaiting this, add it as a note. (Note that we
                # cannot modify the existing context to somehow add the new context into it
                # without causing some programs to report tracebacks that describe control
                # flow that did not actually happen in the program.)
                self.exception.__context__ = context
                del context
    
    
    async def func() -> int:
        raise RuntimeError("i'm func")
    
    
    async def main() -> None:
        container = list[Result[int] | Error[BaseException]]()
        event = Event()
    
        async def acapture(
            func: Callable[P, Awaitable[T]], *args: P.args, **kwargs: P.kwargs
        ) -> None:
            try:
                ret_val = await func(*args, **kwargs)
            except BaseException as exc:
                container.append(Error(exc))
                event.set()
            else:
                container.append(Result(ret_val))
                event.set()
    
        try:
            async with anyio.create_task_group() as tg:
                tg.start_soon(acapture, func)
                await event.wait()
                container.pop().unwrap()
        except BaseExceptionGroup as exc_grp:
            if container and isinstance(result := container.pop(), Error):
                # event.wait() was cancelled.
                raise exc_grp.derive((*exc_grp.exceptions, result.exception))  # noqa: B904
            else:
                raise
        except BaseException as exc:
            if container and isinstance(result := container.pop(), Error):
                # event.wait() was cancelled.
                raise BaseExceptionGroup("some msg", (exc, result.exception))  # noqa: B904
            else:
                raise
        else:
            if container and isinstance(result := container.pop(), Error):
                # event.wait() was cancelled.
                raise BaseExceptionGroup("some msg", (result.exception,))

    It is...challenging...for a user to implement this correctly in a way that (a) won't accidentally swallow the exception and (b) won't give them and their users tracebacks that describe control flows that didn't actually happen. (Actually, I'm not completely certain that the above will not produce incorrect tracebacks; I'd need to write some tests for it.)

    So, do users have use cases for that outcome.acapture-like behavior? My n=1: yes.

    • I have spent a lot of time working on de/multiplexers and this would have been a very useful feature in many of those cases. (Details: You often end up wanting something like (await task_portal.create_task(outcome.acapture, func)).unwrap() when func includes some stateful operation that you can't safely cancel without unrecoverably corrupting the state of something. E.g. if func contains a TLSStream operation, or if func contains multiple subsequent ReliableStream.send calls that together compose a larger protocol message that must remain atomic (even in the face of cancellation of a single protocol-level operation). Without an async-to-async portal, you can also do this with a service task (tricycle.open_service_nursery) and some actor-like inter-task messaging (MemoryObjectStream), but portals are IMO often more convenient and more familiar to Python developers than actors. A portal is just like concurrent.futures.Executor!)

    • A potential/future use case: as nogil increasingly becomes a thing, there will be more people running multiple event loops in one interpreter, and use cases for async-thread-to-async-thread portal calls will probably increase. If we wanted to add cross-threaded-__await__ support to create_task in the future, I suspect it's mostly just a matter of adding some loop_token.run_sync_soon calls and a threading mutex for the shared state.

    (Distantly related request/issue: sync-async-thread-to-async-async-thread portal calls: Run until complete in thread / nested event loops #341/Deadlock when using start_blocking_portal("trio") on trio #525/from_thread.run(_sync)? fails in any thread running Trio python-trio/trio#2534)

    Counterargument 1: The difficult part of implementing this as a user is the "raise the exception out of the group if it was never raised by a TaskHandle" part. A user that can shield their event.wait() call does not have this problem.

    Response to 1: Shielding that is not suitable in the multiplexer cases that I've encountered. When I've been in a situation where I could shield the await task_handle call, I didn't need a TaskHandle in the first place, because I could just replace with shield: (await task_portal.create_task(outcome.acapture, func)).unwrap() with with shield: await func().

    Counterargument 2: It may be surprising to users that the exception of a TaskHandle they abandoned some time ago will wait around until the body of their async with tg exits, and then will get raised. Without automatic cancellation of the entire task group, there is no mechanism to hasten the create_task task's exception being raised somewhere.

    Response to 2: The mechanism to hasten the exception being raised somewhere is await task_handle.

    Response to response to 2: Yes, but it's not difficult for a user to accidentally forget await task_handle, or to await task_handle to get cancelled when they meant to shield it.

    Counterargument 3: TaskGroup.create_task is not intended to be like concurrent.futures.Executor/BlockingPortal. It's intended to be like TaskGroup.start_soon and asyncio.TaskGroup.create_task, which cancel the entire group immediately if the spawned task fails. If someone calls create_task and discards the handle, the behavior should gracefully degrade to exactly the start_soon behavior.

  • "Never-move" semantics (but not "can-move" semantics) make an Exception in a create_task task cancel the other tasks in the task group.

    So, do users have use cases where they want that to happen? Probably. No specific user-use cases have immediately come to my mind, but semantics like this are possibly(?) useful if someone wants to write an API like asyncio.wait(task_handles, return_when=FIRST_EXCEPTION). Take that with a grain of salt though; I haven't actually tried to implement that function.

    Counterargument 4: If someone wanted this behavior but create_task had the "can-move" semantics, it seems pretty straightforward to implement this behavior.

    async def main2() -> None:
        async def cancel_group_on_error(
            task_group: TaskGroup,
            func: Callable[P, Awaitable[T]],
            *args: P.args,
            **kwargs: P.kwargs,
        ) -> T:
            try:
                return await func(*args, **kwargs)
            except Exception:
                task_group.cancel_scope.cancel()
                raise
    
        async with anyio.create_task_group() as tg:
            handle = tg.create_task(cancel_group_on_error(tg, func))
    
            # The tg gets cancelled immediately when func raises:
            await anyio.sleep(10)
    
            # If the user does call await handle, note that it will now raise the exception,
            # whereas with pure never-move semantics it would raise TaskError instead. Is
            # that difference important? If so, we could expose a `handle.wait` that only
            # waits for the event but does not return/raise the captured result or a
            # TaskError.
            await handle

So, my preference here is somewhat mixed:

  • The "can-move" option seems more liberal, i.e. it seems to be suitable for more use cases that the alternative does not support. (At least some of them are use cases that I've spent a lot of time with and am pretty familiar with, but I'm also probably a bit biased because of how such an API would have been quite convenient for me.)

  • The "never-move" option seems to be suitable for (strictly?) fewer use cases, but the behavior in "counterargument 2" could be confusing to users, and "counterargument 3" is convincing to me as well.

Some questions for you all:

  • Are there use cases for "never-move" semantics that are challenging/complicated/impossible to do with "can-move" semantics?

  • Are there ways in which "can-move" semantics are problematic?

    The most compelling thing that I am aware of here is "counterargument 3" above.

Comment thread src/anyio/_core/_tasks.py Outdated
case TaskHandle.Status.CANCELLED:
raise TaskCancelled("the task was cancelled")
case TaskHandle.Status.ERRORED:
raise TaskError("the task raised an exception") from self._exception

@gschaffner gschaffner Mar 28, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This from doesn't seem to be working:

from __future__ import annotations

import traceback

import anyio


async def raiser():
    raise RuntimeError("boom")


async def main() -> None:
    async with anyio.create_task_group() as tg:
        handle = tg.create_task(raiser())
        with anyio.CancelScope(shield=True):
            try:
                await handle
            except BaseException as exc:
                print("".join(traceback.format_exception(exc)).rstrip())
                print()
                raise


anyio.run(main)

gives (CPython 3.13.12)

Traceback (most recent call last):
  File "/home/ganden/vc/anyio/src/anyio/_core/_tasks.py", line 262, in _run_coro
    retval = await self._coro
             ^^^^^^^^^^^^^^^^
  File "/home/ganden/vc/anyio/eg.py", line 9, in raiser
    raise RuntimeError("boom")
RuntimeError: boom

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/ganden/vc/anyio/eg.py", line 17, in main
    await handle
  File "/home/ganden/vc/anyio/src/anyio/_core/_tasks.py", line 321, in __await__
    return self.return_value
           ^^^^^^^^^^^^^^^^^
  File "/home/ganden/vc/anyio/src/anyio/_core/_tasks.py", line 315, in return_value
    raise TaskError("the task raised an exception") from self._exception
anyio.TaskError: the task raised an exception

  + Exception Group Traceback (most recent call last):
  |   File "/home/ganden/vc/anyio/eg.py", line 24, in <module>
  |     anyio.run(main)
  |     ~~~~~~~~~^^^^^^
  |   File "/home/ganden/vc/anyio/src/anyio/_core/_eventloop.py", line 77, in run
  |     return async_backend.run(func, args, {}, backend_options)
  |            ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  |   File "/home/ganden/vc/anyio/src/anyio/_backends/_asyncio.py", line 2358, in run
  |     return runner.run(wrapper())
  |            ~~~~~~~~~~^^^^^^^^^^^
  |   File "/home/ganden/.pyenv/versions/3.13/lib/python3.13/asyncio/runners.py", line 118, in run
  |     return self._loop.run_until_complete(task)
  |            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^
  |   File "/home/ganden/.pyenv/versions/3.13/lib/python3.13/asyncio/base_events.py", line 725, in run_until_complete
  |     return future.result()
  |            ~~~~~~~~~~~~~^^
  |   File "/home/ganden/vc/anyio/src/anyio/_backends/_asyncio.py", line 2341, in wrapper
  |     return await func(*args)
  |            ^^^^^^^^^^^^^^^^^
  |   File "/home/ganden/vc/anyio/eg.py", line 13, in main
  |     async with anyio.create_task_group() as tg:
  |                ~~~~~~~~~~~~~~~~~~~~~~~^^
  |   File "/home/ganden/vc/anyio/src/anyio/_backends/_asyncio.py", line 799, in __aexit__
  |     raise BaseExceptionGroup(
  |         "unhandled errors in a TaskGroup", self._exceptions
  |     ) from None
  | ExceptionGroup: unhandled errors in a TaskGroup (2 sub-exceptions)
  +-+---------------- 1 ----------------
    | Traceback (most recent call last):
    |   File "/home/ganden/vc/anyio/eg.py", line 17, in main
    |     await handle
    |   File "/home/ganden/vc/anyio/src/anyio/_core/_tasks.py", line 321, in __await__
    |     return self.return_value
    |            ^^^^^^^^^^^^^^^^^
    |   File "/home/ganden/vc/anyio/src/anyio/_core/_tasks.py", line 315, in return_value
    |     raise TaskError("the task raised an exception") from self._exception
    | anyio.TaskError: the task raised an exception
    +---------------- 2 ----------------
    | Traceback (most recent call last):
    |   File "/home/ganden/vc/anyio/src/anyio/_core/_tasks.py", line 262, in _run_coro
    |     retval = await self._coro
    |              ^^^^^^^^^^^^^^^^
    |   File "/home/ganden/vc/anyio/eg.py", line 9, in raiser
    |     raise RuntimeError("boom")
    | RuntimeError: boom
    +------------------------------------

The __context__ that we are setting with this from is missing from the exception group rendering.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It works on CPython 3.11 and 3.12, but not 3.10, 3.13, and 3.14. Possibly a CPython regression? I will take a closer look tomorrow.

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

First, I'd like to point out that from doesn't set __context__, it sets __cause__.

This has everything to do with how exception groups are formatted. Consider this:

try:
    raise RuntimeError("boom")
except RuntimeError as exc:
    try:
        raise RuntimeError("another boom") from exc
    except RuntimeError as exc2:
        excgrp = ExceptionGroup("group", (exc, exc2))

print("".join(traceback.format_exception(excgrp)).rstrip())
print("".join(traceback.format_exception(excgrp.exceptions[1])).rstrip())

This results in:

  | exceptiongroup.ExceptionGroup: group (2 sub-exceptions)
  +-+---------------- 1 ----------------
    | Traceback (most recent call last):
    |   File "/home/alex/workspace/anyio/bug-trio.py", line 30, in <module>
    |     raise RuntimeError("boom")
    | RuntimeError: boom
    +---------------- 2 ----------------
    | Traceback (most recent call last):
    |   File "/home/alex/workspace/anyio/bug-trio.py", line 33, in <module>
    |     raise RuntimeError("another boom") from exc
    | RuntimeError: another boom
    +------------------------------------
Traceback (most recent call last):
  File "/home/alex/workspace/anyio/bug-trio.py", line 30, in <module>
    raise RuntimeError("boom")
RuntimeError: boom

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/alex/workspace/anyio/bug-trio.py", line 33, in <module>
    raise RuntimeError("another boom") from exc
RuntimeError: another boom

The __cause__ is indeed preserved but not rendered in the exception group's traceback when the __cause__ is rendered in the traceback.
If we leave out the __cause__ (RuntimeError("boom")) from the exception group, you'll find that the exception is indeed rendered as the cause of the second one:

try:
    raise RuntimeError("boom")
except RuntimeError as exc:
    try:
        raise RuntimeError("another boom") from exc
    except RuntimeError as exc2:
        excgrp = ExceptionGroup("group", (exc2,))

print("".join(traceback.format_exception(excgrp)).rstrip())

Results in:

  | exceptiongroup.ExceptionGroup: group (1 sub-exception)
  +-+---------------- 1 ----------------
    | Traceback (most recent call last):
    |   File "/home/alex/workspace/anyio/bug-trio.py", line 30, in <module>
    |     raise RuntimeError("boom")
    | RuntimeError: boom
    | 
    | The above exception was the direct cause of the following exception:
    | 
    | Traceback (most recent call last):
    |   File "/home/alex/workspace/anyio/bug-trio.py", line 33, in <module>
    |     raise RuntimeError("another boom") from exc
    | RuntimeError: another boom
    +------------------------------------

To summarize, this behavior has nothing whatsoever to do with the task handle's exception handling logic.

@davidbrochart

Copy link
Copy Markdown
Collaborator

But: Task.add_done_callback(), Task.done()...

@agronholm

Copy link
Copy Markdown
Owner Author

But: Task.add_done_callback(), Task.done()...

We don't support adding callbacks, and Task.done() is replaced with the status property.

@davidbrochart

Copy link
Copy Markdown
Collaborator

Sure, I'm just saying asyncio uses "done", but it's fine.

@agronholm

Copy link
Copy Markdown
Owner Author
>>> asyncio.run(main())
<Task finished name='Task-2' coro=<sleep() done, defined at /usr/lib64/python3.10/asyncio/tasks.py:593> result=None>

This is where I originally got the FINISHED state from.

@agronholm

Copy link
Copy Markdown
Owner Author

I'd like to get at least two accepting reviews to ensure some consensus. There's one already, so one more is needed.

@agronholm
agronholm requested review from Graeme22 and m-u-xyz April 14, 2026 11:12

@m-u-xyz m-u-xyz left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well … I'm +.5 on this, because I really dislike asyncio's calling conventions.

But I suppose we can (should, IMHO) add a start_task method (or whatever) later.

@agronholm

Copy link
Copy Markdown
Owner Author

Well … I'm +.5 on this, because I really dislike asyncio's calling conventions.

But I suppose we can (should, IMHO) add a start_task method (or whatever) later.

WDYM? We already have a start() method, and it will be modified later to optionally return a task handle (in a backwards-compatible API change).

@m-u-xyz

m-u-xyz commented Apr 14, 2026

Copy link
Copy Markdown
Collaborator

it will be modified later to optionally return a task handle

Yeah, that was my "or whatever" part.

Sorry if that was too terse / didn't consider past discussion; I'm a bit stressed out at the moment. 😔

Comment thread docs/tasks.rst Resolved
@agronholm
agronholm merged commit 138745c into master Apr 14, 2026
18 checks passed
@agronholm
agronholm deleted the improved-task-group branch April 14, 2026 15:08
@agronholm

Copy link
Copy Markdown
Owner Author

Thanks, now I can continue to the next steps.

alexeyshockov added a commit to alexeyshockov/localpost.py that referenced this pull request May 10, 2026
…ate_task (Future)

start_soon is now fire-and-forget; create_task returns the observation
Future. Aligns with asyncio.TaskGroup and the AnyIO direction in
agronholm/anyio#1098. start_soon is a one-line wrapper over create_task,
so the two share one implementation.

Also swap the eager async-callable check from inspect.iscoroutinefunction
to localpost._utils.is_async_callable, which unwraps functools.partial
and detects callable instances with async __call__.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@tapetersen tapetersen mentioned this pull request Jul 8, 2026
3 tasks done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants