trio icon indicating copy to clipboard operation
trio copied to clipboard

CancelScope should ensure that the current task is the same in __enter__() and __exit__()

Open agronholm opened this issue 4 years ago • 3 comments

The following snippet runs without errors and it shouldn't:

import trio


async def enter_scope(scope):
    scope.__enter__()


async def exit_scope(scope):
    scope.__exit__(None, None, None)


async def main():
    scope = trio.CancelScope()
    async with trio.open_nursery() as nursery:
        nursery.start_soon(enter_scope, scope)
    async with trio.open_nursery() as nursery:
        nursery.start_soon(exit_scope, scope)

trio.run(main)

It should check that the current task in __enter__() and __exit__() are the same.

agronholm avatar Mar 28 '21 22:03 agronholm

Is there an actual reason for such a check? I mean, adding this check just for the sake of having it just slows down correct programs, while incorrect ones tend to go splat anyway IME. Is there even a way to see this unless you're calling __enter__and __exit__ manually (which you shouldn't do in the first place)?

smurfix avatar Mar 29 '21 06:03 smurfix

Calling __enter__() and __exit__() manually is necessary when you embed nurseries or cancel scopes in other context manager classes.

agronholm avatar Mar 29 '21 07:03 agronholm

Mmh. I never do that, I always use either an asynccontextmanager or an asyncexitstack. That stuff is far too easy to get wrong even when only one task is involved.

smurfix avatar Mar 30 '21 07:03 smurfix