I used the order I did because it's idiomatic to return the value the user needs followed by the value the user wants.

On Tue, 13 Jul 2021, 20:24 Serhiy Storchaka, <storchaka@gmail.com> wrote:
13.07.21 18:59, Thomas Grainger пише:
> given that it's hard to implement this correctly I think there should be a builtins.enter and builtins.aenter for use like this:
> ```
> @dataclasses.dataclass
> class WrapCmgr:
>     _cmgr: ContextManager[T]
>     def __enter__(self) -> Wrapped[T]:
>         exit, value = enter(self._cmgr)
>         self.__exit = exit
>         return wrap(value)
>     def __exit__(self, \, t: Type[BaseException] | None, v: BaseException, tb: types.TracebackType) -> bool:
>         return self.__exit(t, v, tb)
> ```

I considered similar idea when worked on issue12022 and issue44471. The
only difference is that I added the helper in the operator module, and
my operator.enter() returned the value and the callback in the different

def enter(cm):
    # We look up the special methods on the type to match the with
    # statement.
    cls = type(cm)
        enter = cls.__enter__
        exit = cls.__exit__
    except AttributeError:
        raise TypeError(f"'{cls.__module__}.{cls.__qualname__}' object
does "
                        f"not support the context manager protocol")
from None
    callback = _MethodType(exit, cm)
    return enter(cm), callback

I still investigate possible consequences and alternatives.

Since we need to save the callback as an object attribute in any case,
one of alternatives is using ExitStack instead of introducing new API.
It is more heavyweight, but if implemented in C the difference can be

Other alternative is to expose _PyObject_LookupSpecial() at Python
level. It would be useful not only for __enter__ and __exit__, but for
other special methods.

Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-leave@python.org
Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/FAQAGFAFVVAKPAU3U6AMFTKUMZCLK2GY/
Code of Conduct: http://python.org/psf/codeofconduct/