Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor run_in_threadpool to seperate binding from execution #1260

Closed
wants to merge 7 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 20 additions & 11 deletions starlette/concurrency.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import functools
import typing
from typing import Any, AsyncGenerator, Iterator
from typing import Any, AsyncGenerator, Awaitable, Iterator

import anyio

Expand All @@ -24,19 +24,28 @@ async def run(func: typing.Callable[[], typing.Coroutine]) -> None:
task_group.start_soon(run, functools.partial(func, **kwargs))


def bind_to_threadpool(
func: typing.Callable[..., T]
) -> typing.Callable[..., Awaitable[T]]:
def inner(*args: typing.Any, **kwargs: typing.Any) -> T:
if contextvars is not None: # pragma: no cover
# Ensure we run in the same context
child = functools.partial(func, *args, **kwargs)
context = contextvars.copy_context()
call = context.run
args = (child,)
elif kwargs: # pragma: no cover
# run_sync doesn't accept 'kwargs', so bind them in here
call = functools.partial(func, **kwargs)
return anyio.to_thread.run_sync(call, *args)

return inner


async def run_in_threadpool(
func: typing.Callable[..., T], *args: typing.Any, **kwargs: typing.Any
) -> T:
if contextvars is not None: # pragma: no cover
# Ensure we run in the same context
child = functools.partial(func, *args, **kwargs)
context = contextvars.copy_context()
func = context.run
args = (child,)
elif kwargs: # pragma: no cover
# run_sync doesn't accept 'kwargs', so bind them in here
func = functools.partial(func, **kwargs)
return await anyio.to_thread.run_sync(func, *args)
return await bind_to_threadpool(func)(*args, **kwargs)


class _StopIteration(Exception):
Expand Down