[issue37398] contextlib.ContextDecorator decorating async functions

Nick Coghlan report at bugs.python.org
Tue Sep 3 04:15:02 EDT 2019


Nick Coghlan <ncoghlan at gmail.com> added the comment:

It isn't the simple case where the auto-detection idea concerns me, it's decorator stacking cases like:

    @outer
    @magic_detection
    @inner_forces_async
    def sync_native_api():
        ...

(With the original asyncio.coroutine being one example, but there are other situations where this comes up, like a wrapper that bundles synchronous calls up into an executor invocation)

That said, I'd be completely fine with a combination where:

* ContextDecorator grew a coroutine() classmethod (open to suggestions for bikeshed colours)
* The regular ContextDecorator constructor emitted a warning suggesting "cls.coroutine" when it was applied to a synchronous function

Then the original example would provide distinct spellings for the sync and async case, without the definition of PerfTimer needing to change:

  @PerfTimer.coroutine('query_async')
  async def query_or_throw(self, q):
      return _parse_result(await self._send_query(q))

  @PerfTimer('query_sync')
  def query_or_throw(self, q):
      return _parse_result(self._send_query_sync(q))

That way we're still refusing to guess in the face of ambiguity (does the user want the coroutine version of the context manager, or did they accidentally mix a potentially blocking synchronous context manager into their async code?), but the warning can be usefully explicit regarding how to resolve the ambiguity.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue37398>
_______________________________________


More information about the Python-bugs-list mailing list