# Raise an error when entering an AsyncExitStack without a context?

**URL:** <https://discuss.python.org/t/raise-an-error-when-entering-an-asyncexitstack-without-a-context/107321>\
**Category:** Ideas\
**Created:** [May 11, 2026, 3:50pm UTC](https://discuss.python.org/t/raise-an-error-when-entering-an-asyncexitstack-without-a-context/107321 "2026-05-11T15:50:17Z")\
**Posts on this page:** 16\
**Page:** 1

<div class="post-metadata">

**Author:** ![smurfix](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/smurfix/32/704_2.png) [@smurfix](https://discuss.python.org/u/smurfix)\
**Post date:** [May 11, 2026, 3:50pm UTC](https://discuss.python.org/t/raise-an-error-when-entering-an-asyncexitstack-without-a-context/107321/1 "2026-05-11T15:50:17Z")

</div>

This code

```python
    stack = AsyncExitStack()
    await stack.enter_async_context(open_connection())

```

(no async context, no error handling …) arguably is broken, yet doesn’t raise an exception or anything.

IMHO this should warn, or even raise a `RuntimeError`.

---

<div class="post-metadata">

**Author:** ![jsbueno](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/jsbueno/32/1210_2.png) [@jsbueno](https://discuss.python.org/u/jsbueno)\
**Post date:** [May 13, 2026, 1:28am UTC](https://discuss.python.org/t/raise-an-error-when-entering-an-asyncexitstack-without-a-context/107321/2 "2026-05-13T01:28:20Z")

</div>

Why should it?  
This is something to be used by people knowing how to use it - that said, it is perfectly legal to be used “bare”: either the `.aclose` or `\__aexit_\_` methods can be explicitly called later.

While it may be hard to think of a use case for that in scripted/programmed code, it is a useful pattern in the REPL, for example: and just forbidding that would let one no work around should they want to type interactive expressions inside several contexts (as opposed to having to type all expressions within a `with` block and have they all run at once)

Not to mention that while mandating an active async context by “enabling” the “enter\_context” just after `\__aenter_\_` is called would be a simple _change_ it would nonetheless be a backwards incompatible change at this point (the same for the sync “ExitStack”), the other scenario: detecting if errors are being handled, i.e. if it is called inside a `try` block, would require pretty hardcore introspection involving both Frame and possibly even runtime bytecode introspection - the gains would be minimal.

This sounds like something that static checkers (linters, etc…) could do - but I can’t see how changing the runtime to error on a perfectly valid statement would be of help.

---

<div class="post-metadata">

**Author:** ![tapetersen](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/tapetersen/32/28049_2.png) [@tapetersen](https://discuss.python.org/u/tapetersen)\
**Post date:** [May 13, 2026, 7:45am UTC](https://discuss.python.org/t/raise-an-error-when-entering-an-asyncexitstack-without-a-context/107321/3 "2026-05-13T07:45:57Z")

</div>

> [@jsbueno](#):
>
> it is perfectly legal to be used “bare”: either the `.aclose` or `_*aexit*_` methods can be explicitly called later.

That would still be a preserved. You would just call ` __aenter__ `first.

> [@jsbueno](#):
>
> is a useful pattern in the REPL, for example: and just forbidding that would let one no work around should they want to type interactive expressions inside several contexts (as opposed to having to type all expressions within a `with` block and have they all run at once)

I don’t see how that usage would be stopped by just requiring “entering” it first.

> [@jsbueno](#):
>
> Not to mention that while mandating an active async context by “enabling” the “enter\_context” just after `_*aenter*_` is called would be a simple _change_ it would nonetheless be a backwards incompatible

Because of this a warning at first seems very reasonable (as was suggested) but with that I don’t see why it should be an issue.

> [@jsbueno](#):
>
> This sounds like something that static checkers (linters, etc…) could do - but I can’t see how changing the runtime to error on a perfectly valid statement would be of help.

It would be an appropriate lint rule sure but it’s not unusual to store the exit stacks on objects where the linter won’t have the context to detect if it’s opened or not (and it’s also those cases that most likely leads to the harder to debug cases)

One point to it being an actual used case is [this example](https://docs.python.org/3/library/contextlib.html#catching-exceptions-from-enter-methods) from the stdlib documentation.

```python
stack = ExitStack()
try:
    x = stack.enter_context(cm)
except Exception:
    # handle __enter__ exception
else:
    with stack:
        # Handle normal case

```

It too can be solved with calling enter manually and then `pop_all()`in the exception block.  
Edit: or probably better by something like

```python
try:
    x = cm. __enter__ ()
except Exception:
    # handle __enter__ exception
else:
    with ExitStack() as stack:
        stack.push(cm)
        # Handle normal case

```

---

<div class="post-metadata">

**Author:** ![tapetersen](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/tapetersen/32/28049_2.png) [@tapetersen](https://discuss.python.org/u/tapetersen)\
**Post date:** [June 10, 2026, 9:51am UTC](https://discuss.python.org/t/raise-an-error-when-entering-an-asyncexitstack-without-a-context/107321/4 "2026-06-10T09:51:46Z")

</div>

This didn’t get any more traction. If no one weighs in I’ll probably open an issue and/or PR for it (if @smurfix doesn’t do it first…)

---

<div class="post-metadata">

**Author:** ![picnixz](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/picnixz/32/12660_2.png) [@picnixz](https://discuss.python.org/u/picnixz)\
**Post date:** [June 10, 2026, 12:39pm UTC](https://discuss.python.org/t/raise-an-error-when-entering-an-asyncexitstack-without-a-context/107321/5 "2026-06-10T12:39:43Z")

</div>

If `open_connection()` is `asyncio.open_connection()`, using `python -m asyncio`, I get:

```python
>>> import contextlib
>>> s = contextlib.AsyncExitStack()
>>> await s.enter_async_context(asyncio.open_connection())
TypeError: 'builtins.coroutine' object does not support the asynchronous context manager protocol

```

So I do see an error. As such, unless you explain what `open_connection()` is meant to do and what it should return, I don’t think there is anything to change.

---

<div class="post-metadata">

**Author:** ![tapetersen](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/tapetersen/32/28049_2.png) [@tapetersen](https://discuss.python.org/u/tapetersen)\
**Post date:** [June 10, 2026, 1:24pm UTC](https://discuss.python.org/t/raise-an-error-when-entering-an-asyncexitstack-without-a-context/107321/6 "2026-06-10T13:24:54Z")

</div>

That’s just a mistake in that it’s an async function returning an `AsyncContextManager` so you have to await it (and supply correct arguments). The issue here applies to any `ContextManager`, async or not.

The risk here would be that since `(Async)ExitStack. __enter__ ()` itself hasn’t been called yet it’s not in a with block and as such there is likely no exit that will actually call the added context’s `__(a)exit__(...)`

```python
import asyncio
import contextlib

class Resource:

    async def __aenter__ (self):
        print("Allocated resource")

    async def __aexit__ (self, *exc_info):
        print("De-allocated resource")

async def main():

    s = contextlib.AsyncExitStack()
    await s.enter_async_context(Resource()) # Will print "Allocated resource"

    # Resource is never deallocated

asyncio.run(main())

```

In reality where this has been seen it’s usually where an `ExitStack` is part of an object which is itself a resource for example.

---

<div class="post-metadata">

**Author:** ![picnixz](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/picnixz/32/12660_2.png) [@picnixz](https://discuss.python.org/u/picnixz)\
**Post date:** [June 10, 2026, 1:30pm UTC](https://discuss.python.org/t/raise-an-error-when-entering-an-asyncexitstack-without-a-context/107321/7 "2026-06-10T13:30:05Z")

</div>

Ah, the problem is entering AsyncExitStack itself. I thought the problem was what was entered. Then no, we don’t want to change this because it’s the user responsibility to close the context manager. It’s not uncommon to pass around stacks if you need to compose with others.

---

<div class="post-metadata">

**Author:** ![tapetersen](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/tapetersen/32/28049_2.png) [@tapetersen](https://discuss.python.org/u/tapetersen)\
**Post date:** [June 10, 2026, 6:25pm UTC](https://discuss.python.org/t/raise-an-error-when-entering-an-asyncexitstack-without-a-context/107321/8 "2026-06-10T18:25:52Z")

</div>

I’m not insisting very heavily on this and am personally prepared to concede it on simple churn/benefit analysis (especially with needing to warn on a documented pattern).

I’m not sure I follow the objection of responsibility on a categorical level though. If something is a bug substantially more often than not and the fix in the cases where it’s intended is trivial and arguably clarifying some small rate of false positives of warnings could be acceptable?

I’m also not sure how this precludes passing stacks around or burdens that pattern. In most cases of that I’ve seen the stacks are still entered/exited and simply uses pop\_stack to transfer/compose what’s needed.

Unless there is some other positive swing I won’t file any issue or PR.

> **stdlib use**
>
> For interest I tried searching through the standard library for the pattern and found 1 use in the unittest module and 11 more in test-cases. All would be trivially fixed and arguably clarified by an explicit ` __enter__ `

---

<div class="post-metadata">

**Author:** ![smurfix](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/smurfix/32/704_2.png) [@smurfix](https://discuss.python.org/u/smurfix)\
**Post date:** [June 11, 2026, 9:39am UTC](https://discuss.python.org/t/raise-an-error-when-entering-an-asyncexitstack-without-a-context/107321/9 "2026-06-11T09:39:02Z")

</div>

> [@picnixz](#):
>
> Then no, we don’t want to change this because it’s the user responsibility to close the context manager.

My point exactly: it’s a **context manager**. You use a context manager by calling ` __enter__ ` and ` __exit__ `, and you do _that_, in idiomatic python, by way of `[async] with …:`, which incidentally passes the responsibility for actually calling ` __exit__ ` to the Python interpreter, which reduces boilerplate clutter as well as line count and bug surface.

> [@picnixz](#):
>
> It’s not uncommon to pass around stacks if you need to compose with others.

You can still do that. You just need one single chunk of code that’s actually responsible for opening _and_ closing the context, instead of spreading that responsibility around. I’d contend that the latter is sufficiently uncommon; if your code _really_ needs that pattern (a) your spaghetti structure wants to be refactored, (b) there’s nothing that prevents you from calling the dunder methods explicitly.

Also, when you use async contexts and taskgroups (or the library you’re using does) the whole idea of opening an async exit stack _here_ and closing it _there_ is no longer viable: you must not break taskgroup nesting.

---

<div class="post-metadata">

**Author:** ![picnixz](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/picnixz/32/12660_2.png) [@picnixz](https://discuss.python.org/u/picnixz)\
**Post date:** [June 11, 2026, 1:11pm UTC](https://discuss.python.org/t/raise-an-error-when-entering-an-asyncexitstack-without-a-context/107321/10 "2026-06-11T13:11:16Z")

</div>

In the example I was given, namely:

```python
import asyncio
import contextlib

class Resource:

    async def __aenter__ (self):
        print("Allocated resource")

    async def __aexit__ (self, *exc_info):
        print("De-allocated resource")

async def main():

    s = contextlib.AsyncExitStack()
    await s.enter_async_context(Resource()) # Will print "Allocated resource"

    # Resource is never deallocated

asyncio.run(main())

```

AFAIU, the problem is that the resource is never deallocated. Ok, but that’s the caller responsibility. They decided not to use a context manager so they are on their own for managing their resources. They must themselves call `await s.aclose()` when necessary. Or do `async with s: [...]`.

It is also documented in ExitContext already:

> Each instance maintains a stack of registered callbacks that are called in reverse order when the instance is closed (either explicitly or implicitly at the end of a with statement). Note that callbacks are not invoked implicitly when the context stack instance is garbage collected.

So, once the caller decide _not_ to use it as a real context manager, they MUST call explicitly close()/aclose().

---

<div class="post-metadata">

**Author:** ![tapetersen](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/tapetersen/32/28049_2.png) [@tapetersen](https://discuss.python.org/u/tapetersen)\
**Post date:** [June 11, 2026, 1:45pm UTC](https://discuss.python.org/t/raise-an-error-when-entering-an-asyncexitstack-without-a-context/107321/11 "2026-06-11T13:45:32Z")

</div>

> [@picnixz](#):
>
> So, once the caller decide _not_ to use it as a real context manager, they MUST call explicitly close()/aclose().

The call for this came from a real bug with a hairy debug situation where that _wasn’t_ apparent to a user.

The argument for warning is that it would nudge them towards using a with block (or Enter it into another `ContextStack`) and I have yet to see a single example where the existing pattern could be used as is with the only needed difference being an explicit call to `__(a)enter__` when constructed (even in the doc sample above that would work for simply silencing a warning as it ` __enter__ ` would still be idempotent)

> [@smurfix](#):
>
> Also, when you use async contexts and taskgroups (or the library you’re using does) the whole idea of opening an async exit stack _here_ and closing it _there_ is no longer viable: you must not break taskgroup nesting.

Currently that is the case most often triggering this but that required nesting invariant really applies to more `ContextManager`s . The bugs are often just more subtle and harder to trigger other than on shutdown where errors are often tolerated and discarded. (I just don’t want this to be seen as an argument introduced only for structured concurrency, it’s more fundamental than that. For example [contextlib.chdir](https://docs.python.org/3/library/contextlib.html#contextlib.chdir), [decimal.localcontext](https://docs.python.org/3/library/decimal.html#decimal.localcontext)

---

<div class="post-metadata">

**Author:** ![picnixz](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/picnixz/32/12660_2.png) [@picnixz](https://discuss.python.org/u/picnixz)\
**Post date:** [June 11, 2026, 2:02pm UTC](https://discuss.python.org/t/raise-an-error-when-entering-an-asyncexitstack-without-a-context/107321/12 "2026-06-11T14:02:37Z")

</div>

> [@tapetersen](#):
>
> The call for this came from a real bug with a hairy debug situation where that _wasn’t_ apparent to a user.

I’m sorry but this is not enough for raising a warning where legitimate code would be annoyed.

> and I have yet to see a single example where the existing pattern could be used as is

I’m not sure if my answer will be the answer to this as I’m not sure I understood correctly what you meant by “existing pattern”, but there are some examples of entering the stack as is without using it as a context:

> <https://github.com/python/cpython/blob/0066fd73a20950dc790d219f4e3cfb07e816df47/Lib/test/test_importlib/resources/test_custom.py#L37-L48>

> <https://github.com/python/cpython/blob/0066fd73a20950dc790d219f4e3cfb07e816df47/Lib/test/test_zipfile/_path/test_path.py#L85-L89>

This is clearly something that frameworks may rely on, and even custom projects.

---

<div class="post-metadata">

**Author:** ![smurfix](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/smurfix/32/704_2.png) [@smurfix](https://discuss.python.org/u/smurfix)\
**Post date:** [June 11, 2026, 2:21pm UTC](https://discuss.python.org/t/raise-an-error-when-entering-an-asyncexitstack-without-a-context/107321/13 "2026-06-11T14:21:53Z")

</div>

> [@picnixz](#):
>
> This is clearly something that frameworks may rely on, and even custom projects.

So? People also relied on being able to do

```python
    try:
        ....
    finally:
        ....
        return

```

and we decided to warn about that pattern anyway.

---

<div class="post-metadata">

**Author:** ![picnixz](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/picnixz/32/12660_2.png) [@picnixz](https://discuss.python.org/u/picnixz)\
**Post date:** [June 11, 2026, 2:33pm UTC](https://discuss.python.org/t/raise-an-error-when-entering-an-asyncexitstack-without-a-context/107321/14 "2026-06-11T14:33:17Z")

</div>

PEP-765 (which AFAIR remains controversial) was proposed because there were hardly any projects that were using it correctly. This is not the same for `ExitStack` and this is not the same level of issues.

The API on ExitStacks is well-documented, and still documented as being low-level. Adding a warning would defeat the purpose of using its methods outside a `with` context.

I will step down from this discussion because you won’t be able to convince me that it is useful nor desired and I don’t have more time to convince you that emitting warnings or raising errors for _legitimate_ patterns will affect downstream users. Leaking resources are usually reported at interpreter finalization so it’s also not impossible to debug.

---

<div class="post-metadata">

**Author:** ![tapetersen](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/tapetersen/32/28049_2.png) [@tapetersen](https://discuss.python.org/u/tapetersen)\
**Post date:** [June 11, 2026, 2:52pm UTC](https://discuss.python.org/t/raise-an-error-when-entering-an-asyncexitstack-without-a-context/107321/15 "2026-06-11T14:52:15Z")

</div>

> [@picnixz](#):
>
> I’m sorry but this is not enough for raising a warning where legitimate code would be annoyed.

It may very well be the conclusion since the cost for false warnings from the stdlib is quite high. I’m just not convinced the prevalence of uses and the purported hassle of fixing them aren’t overestimated.

- How common is the existing pattern?  
Single use in non-test code (`unittest.mock`) 10 more in tests as the examples shown above. All fixable by adding single ` __enter__ ()` call inline on construct or on following line.  
Third party code I don’t have a simple way to check yet but I would imagine a large majority of the `addCleanup` pattern in tests and actually quite few otherwise as people seem to actually use the `ExitStacks` a lot less than they should.

- How annoying disruptive are the warnings?  
I would say lower than expected from frequency since they in many cases would only be in tests.

- How hard is the intended fix?  
Trivial (add a call to ` __enter__ `) and could probably be explicitly documented in the warning

- How common is the error it catches and what is the impact if not?  
Not that common but I would say it definitely can lead to nasty debugging when it does.

> [@picnixz](#):
>
> This is clearly something that frameworks may rely on, and even custom projects.

They still can at the cost of detecting a warning and suppressing it with a very simple modification. Not a zero cost but very far from not being able to rely on.

---

<div class="post-metadata">

**Author:** ![tapetersen](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/tapetersen/32/28049_2.png) [@tapetersen](https://discuss.python.org/u/tapetersen)\
**Post date:** [June 11, 2026, 3:15pm UTC](https://discuss.python.org/t/raise-an-error-when-entering-an-asyncexitstack-without-a-context/107321/16 "2026-06-11T15:15:05Z")

</div>

> [@picnixz](#):
>
> I will step down from this discussion because you won’t be able to convince me that it is useful nor desired and I don’t have more time to convince you that emitting warnings or raising errors for _legitimate_ patterns will affect downstream users.

I’m fully aware this will affect some _legitimate_ downstream users and have never argued otherwise. I’m not trying to convince you it won’t, just to leave some room for consideration despite that.

My own position is probably a cautious +0.5 but I fully expect and respect the position of treating warnings for legitimate code being near unacceptable as well.

Edit: Note below

For posterity I’ve been mainly concerned about it being clear that the proposal amounts to, a warning for some legitimate cases with a one-line fix, and not a forced re-write to with-blocks or other refactoring.
