4 ms·
You perfectly illustrated why this is a problem. Calling functions from one side to the other involves ceremony. Ceremony adds cognitive overhead and decreases
by WoodenChair 6y ago
You perfectly illustrated why this is a problem. Calling functions from one side to the other involves ceremony. Ceremony adds cognitive overhead and decreases readability.
- PaulHoule 6y agoI've written Python functions that "call" another function either async or not depending on how the function inspects. For instance, imagine a "maybe_await" method that just calls sync if is synchronous or otherwise awaits.
- mattbillenstein 6y agoIt's very heavy to do this is it not? Like you inspect the function on each call to figure out if it's async or not?
- PaulHoule 6y agoFor things that happen at UI speed it isn't bad. If I wanted to do something a million times a second I'd worry about it. Some Javascript frameworks, such as Vue, often do something similar in that you can pass either a sync or async callback and it does the right thing for either. In that case you could potentially inspect the function once and call it many times.
- 1337shadow 6y agoYou don't inspect the function, but the result. Is it a coroutine ? If so, it needs to be awaited (see my example above). I believe this also would allow non-async function to return a coroutine I suppose. Anyway, in this case chances are that there will be no performance overhead if there's any io bound operation running in the coroutine so it should run the iscoroutine check of the result and the await call before the function is done.
- 1337shadow 6y agoThat's trivial: result = yourfunc() if inspect.iscoroutine(result): result = asyncio.run(result) If I have code like that, it's at one place per library, didn't need to encapsulate it in a maybe_await function.
- 1337shadow 6y agoWould that work for you ? result = asyncio.run(red(x)) That's calling async function red from non-async code. Not seeing any particular readability issue with that usage neither. If you don't call asyncio.run or await on the result of an async function call, then you get a coroutine for result.
- WoodenChair 6y ago> result = asyncio.run(red(x)) Still much harder to think about/read then result = red(x) We should be finding ways to get to the latter with concurrency. async/await is at best a patchwork compromise until we can do better.
- joshuamorton 6y agoI much prefer the performance implications of my code be explicit than implicit. Async in this case has less ceremony than threads. But still enough to make thing explicit.