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
order.

def enter(cm):
    # We look up the special methods on the type to match the with
    # statement.
    cls = type(cm)
    try:
        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
reduced.

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-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.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/

Reply via email to