Copy of defer.maybeDeferred that also converts coroutines to Deferreds.
(
f: Callable[_P, Any], warn: bool, *args: _P.args, **kw: _P.kwargs
)
| 432 | |
| 433 | |
| 434 | def _maybeDeferred_coro( |
| 435 | f: Callable[_P, Any], warn: bool, *args: _P.args, **kw: _P.kwargs |
| 436 | ) -> Deferred[Any]: |
| 437 | """Copy of defer.maybeDeferred that also converts coroutines to Deferreds.""" |
| 438 | try: |
| 439 | result = f(*args, **kw) |
| 440 | except: # noqa: E722 |
| 441 | return fail(failure.Failure(captureVars=Deferred.debug)) |
| 442 | |
| 443 | # when the deprecation period has ended we need to make sure the behavior |
| 444 | # of the public maybeDeferred_coro() function isn't changed, or drop it in |
| 445 | # the same release |
| 446 | if isinstance(result, Deferred): |
| 447 | if warn: |
| 448 | warnings.warn( |
| 449 | f"{global_object_name(f)} returned a Deferred, this is deprecated." |
| 450 | f" Please refactor this function to return a coroutine.", |
| 451 | ScrapyDeprecationWarning, |
| 452 | stacklevel=2, |
| 453 | ) |
| 454 | return result |
| 455 | if asyncio.isfuture(result) or inspect.isawaitable(result): |
| 456 | return deferred_from_coro(result) |
| 457 | if isinstance(result, failure.Failure): # pragma: no cover |
| 458 | if warn: |
| 459 | warnings.warn( |
| 460 | f"{global_object_name(f)} returned a Failure, this is deprecated." |
| 461 | f" Please refactor this function to return a coroutine.", |
| 462 | ScrapyDeprecationWarning, |
| 463 | stacklevel=2, |
| 464 | ) |
| 465 | return fail(result) |
| 466 | return succeed(result) |
| 467 | |
| 468 | |
| 469 | def deferred_to_future(d: Deferred[_T]) -> Future[_T]: |
no test coverage detected