Repository navigation
Closed
Labels
Description
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
assignee = None
closed_at = <Date 2020-05-21.05:58:41.914>
created_at = <Date 2017-12-13.19:54:21.835>
labels = ['docs', '3.9', 'expert-asyncio']
title = 'Implement asyncio.run_in_executor shortcut'
updated_at = <Date 2020-05-21.05:58:41.913>
user = 'https://github.com/asvetlov'bugs.python.org fields:
activity = <Date 2020-05-21.05:58:41.913>
actor = 'aeros'
assignee = 'none'
closed = True
closed_date = <Date 2020-05-21.05:58:41.914>
closer = 'aeros'
components = ['Documentation', 'asyncio']
creation = <Date 2017-12-13.19:54:21.835>
creator = 'asvetlov'
dependencies = []
files = []
hgrepos = []
issue_num = 32309
keywords = ['patch']
message_count = 43.0
messages = ['308238', '308239', '308243', '308245', '341352', '355771', '355773', '355796', '355798', '355799', '355800', '355802', '355804', '355805', '355807', '355809', '355811', '355842', '355846', '355852', '355854', '355855', '355857', '355858', '355862', '355863', '355881', '355883', '355938', '355957', '355975', '355978', '356242', '356303', '356776', '356792', '360725', '369318', '369331', '369408', '369493', '369495', '369497']
nosy_count = 7.0
nosy_names = ['vstinner', 'asvetlov', 'chris.jerdonek', 'yselivanov', 'miss-islington', 'primal', 'aeros']
pr_nums = ['4848', '18410', '20143', '20212', '20278', '20279']
priority = 'normal'
resolution = 'fixed'
stage = 'resolved'
status = 'closed'
superseder = None
type = None
url = 'https://bugs.python.org/issue32309'
versions = ['Python 3.9']
Activity
asvetlov commentedon Dec 13, 2017
loop.create_task() and loop.run_in_executor are present very often in user code. But they are require a loop instance, actual call looks like
The proposal adds create_task(coro) and run_in_executor(executor, func, *args) shortcuts for this.
1st1 commentedon Dec 13, 2017
I don't like the low-level API of run_in_executor. "executor" being the first argument, the inability to pass **kwargs, etc.
I'd expect to see a more high-level API, perhaps the one that supports 'async with':
I mean it's great that we can use 'concurrent.futures' in asyncio, but having native asyncio pools implementation would be way more convenient to the users.
In any case, can we focus this issue on the "run_in_executor" API, and open a new one for "create_task"?
asvetlov commentedon Dec 13, 2017
Removed create_task() from title
[-]Implement asyncio.create_task() and asyncio.run_in_executor shortcuts[/-][+]Implement asyncio.run_in_executor shortcut[/+]asvetlov commentedon Dec 13, 2017
https://bugs.python.org/issue32311 opened for create_task()
asvetlov commentedon May 3, 2019
In Python 3.7 loop.run_in_executor() is the only user-faced method that requires a loop.
asyncio.ThreadPool() sounds great. Maybe thread group can provide better api.
But for Python 3.8 adding
run_in_executortop-level function looks the only easy and obvious way to help people getting rid of explicit loop usage.Yuri, what do you think?
aeros commentedon Oct 31, 2019
I agree that there's an issue with this, but I think for the high level API it can be an asynchronous context manager that makes use of concurrent.futures.ThreadPoolExecutor, since that one seems to fit the majority of asyncio use cases. If users want to utilize concurrent.futures.ProcessPoolExecutor or a customized one, they can use loop.run_in_executor() instead.
Unless there's something I'm missing with regards to concurrent.futures.ThreadPoolExecutor that specifically makes it less usable. Can't asyncio.ThreadPool make use of concurrent.futures.ThreadPoolExecutor in the internal details while providing a better API?
I'd be willing to work on implementing the asyncio.ThreadPool API as Yury described it.
I can see your point Andrew, but I think that if we implement asyncio.run_in_executor() and then later add asyncio.ThreadPool(), it's going to be against "one obvious way" and we'll end up adding two high-level functions for the same purpose. This principle can't always be adhered to, but I think we should try to when it's possible.
Personally, I think the API for asyncio.ThreadPool would be much more robust, so it seems worthwhile to try implementing this one first. If there are a number of unforeseen complications, asyncio.run_in_executor() might still be a decent fallback.
aeros commentedon Oct 31, 2019
Clarification: asyncio.run_in_executor() would be a function, but asyncio.ThreadPool would be a context manager class.
aeros commentedon Nov 1, 2019
So, here's a prototype implementation of asyncio.ThreadPool that would function exactly as Yury described, but I'm not convinced about the design. Usually, it seems preferred to separate the context manager from the rest of the class (as was done with asyncio.Lock), but I think this one might be simple enough to be a single class:
It utilizes the existing lower level event loop API to provide an asynchronous context manager. I'd say the main advantage is that it's significantly more user friendly, as there's no loop or executor argument to be specified, and users can freely pass kwargs to run() thanks to functools.partial().
Additionally, I also included a timeout parameter for shutting down the ThreadPoolExecutor, which will depend upon #60564. This can be used as such:
I don't expect that this would be the final design, but I think it's a decent prototype to demonstrate the functionality. Thoughts?
asvetlov commentedon Nov 1, 2019
runshould be awaitable method, see bpo-3843023 remaining items
1st1 commentedon Nov 8, 2019
Correct.
Correct. There are a few points of this approach:
(a) design the API correctly;
(b) ship something that definitely works with a proven ThreadPoolExecutor;
(c) write lots of tests;
(d) write docs;
(e) if (a-d) are OK, refine the implementation later by replacing ThreadPoolExecutor with a proper (eager threads creation) implementation.
Yeah. In your current approach you're using ThreadPoolExecutor private API, which makes the code a bit fragile. There are two alternatives:
Extent ThreadPoolExecutor API to add an option of eager threads spawn.
Not using ThreadPoolExecutor at all. We can write our own threads orchestration code, it's not that complicated. If we do that, our implementation will become quite faster than the current run_in_executor. We can use curio as inspiration. Last time I profiled asyncio I saw that the code binding concurrent.Future to asyncio.Future is quite complex, brittle, and slow.
I'm in favor of (2), but let's go through (a-d) steps to get there.
aeros commentedon Nov 9, 2019
That sounds like a good strategy. I'll start working on step a, to build a more robust working implementation (that only uses ThreadPoolExecutor's public API), and then work on c and d once the API is approved.
Agreed, I'm also in favor of option (2), but doing (a-d) first. I think this approach will provide far more stability (rather than implementing (2) immediately), as we'll be able to write extensive test coverage using a ThreadPoolExecutor implementation as a base, and then ensure the native asyncio threadpool implementation has the same intended behavior. Afterwards, could even keep the ThreadPoolExecutor version as private for testing purposes.
The native asyncio version will likely require some additional tests to ensure that the threads are being spawned eagerly, but they should have very similar overall behavior, with the asyncio version having better performance.
I'm thinking that we could create a new Lib/asyncio/pools.py, for the initial ThreadPoolExecutor implementation, to give us a separate area to work with for native asyncio one in the future. A similar asyncio.ProcessPool API could also be eventually created there as well. It might be feasible to fit the initial implementation in Lib/asyncio/base_events.py, but IMO the native asyncio version would not fit.
(From the user end it would make no difference, as long as we add pools.__all__ to Lib/asyncio/init.py)
My only remaining question that I can think of: should we implement an asyncio.ProcessPool API (using ProcessPoolExecutor's public API) before working on the native asyncio version of asyncio.ThreadPool?
This would likely allow us to release the executor versions well before the 3.9 beta (2020-05-18), and then the native asyncio versions (with eager spawning) either before 3.9rc1 (2020-08-10) or at some point during 3.10 alpha. I suspect that writing the extensive test coverage will take the most time.
aeros commentedon Nov 16, 2019
Yury and Andrew, here's my latest API design for asyncio.ThreadPool: master...aeros:asyncio-threadpool. This is for the initial ThreadPoolExecutor version, using the design based on Yury's suggestions. I plan on extending upon the docstrings, writing tests, and the documentation for it.
My idea was to use the new Lib/asyncio/pools.py and AbstractPool to eventually implement an asyncio.ProcessPool (and the native version of asyncio.ThreadPool).
I plan on opening a PR after I finish writing some tests and documentation, I'd like to include it all in the same PR if possible. But let me know what you think about the current API design, it would be much easier for me to make modifications at this stage.
aeros commentedon Nov 17, 2019
So, I just had an interesting idea... what if ThreadPool.run() returned a Task instead of a coroutine object?
With the current version of asyncio.ThreadPool, if a user wants to create a Task, they would have to do something like this:
To me, this looks like excessive boilerplate, particularly for a higher level API. Even for rather straightforward behavior, it requires nested function calls. If we were to return a task directly, this would be significantly cleaner:
Since asyncio.ThreadPool is intended to be a high-level API, I don't think it's an issue to return a Task from it's run() method. It would make it significantly easier and more convenient to work with from a user perspective.
Thoughts?
aeros commentedon Jan 26, 2020
After having some time to think this over, I prefer the current behavior. I don't think there would be significant enough improvement from returning a Task instead, and it would likely result in an overall performance loss.
Also, as a general update on the project, I'm close to being ready to open a PR to implement asyncio.ThreadPool. I finished the basic implementation and added a decent number of new tests to ensure its functionality. Here's my current progress: master...aeros:asyncio-threadpool
I just need to work on adding the new documentation, and more specifically finding a good place for it in the current asyncio docs. Do you have any ideas for that, Yury? I figured that you might already have a preference in mind.
miss-islington commentedon May 19, 2020
New changeset cc2bbc2 by Kyle Stanley in branch 'master':
bpo-32309: Implement asyncio.to_thread() (GH-20143)
cc2bbc2
miss-islington commentedon May 19, 2020
New changeset e299130 by Miss Islington (bot) in branch '3.9':
bpo-32309: Implement asyncio.to_thread() (GH-20143)
e299130
vstinner commentedon May 20, 2020
Note for myself: Python 3.9 release manager (Lukasz) approved adding the feature to Python 3.9.0 beta2:
#20212 (review)
miss-islington commentedon May 21, 2020
New changeset 0f56263 by Kyle Stanley in branch 'master':
bpo-32309: Add support for contextvars in asyncio.to_thread() (GH-20278)
0f56263
miss-islington commentedon May 21, 2020
New changeset 3e65054 by Miss Islington (bot) in branch '3.9':
bpo-32309: Add support for contextvars in asyncio.to_thread() (GH-20278)
3e65054
aeros commentedon May 21, 2020
Now that the
versionaddedlabel has been added and the contextvar issue was addressed, this issue can be closed.