| ▲ | amluto 5 hours ago | |
I can't quite parse what you're saying. Python works like this:
Running it does this:
So there mere act of creating a coroutine does not cause the runtime to run it. But if you explicitly create a task, it does get run:
I personally like the behavior of coroutines not running unless you tell them to run -- it makes it easier to reason about what code runs when. But I do not particularly like the way that Python obscures the difference between a future-like thing that is a coroutine and a future-like thing that is a task. | ||
| ▲ | int_19h an hour ago | parent | next [-] | |
> I personally like the behavior of coroutines not running unless you tell them to run -- it makes it easier to reason about what code runs when. In .NET the difference was known as "hot" vs "cold" tasks. "Hot" tasks - which is what .NET does with C# async/await - have one advantage in that they get to run any code that validates the arguments right away and fail right there at the point of the call, which is easier to debug. But one can argue that such validation should properly be separate from function body in the first place - in DbC terms it's the contract of the function. | ||
| ▲ | throwup238 2 hours ago | parent | prev | next [-] | |
That’s exactly the behavior I’m describing. `sleepy_future = sleepy()` creates the state machine without running anything, `create_task` actually schedules it to run via a queue, `asyncio.sleep` suspends the main task so that the newly scheduled task can run, and `await sleepy_task` either yields the main task until sleepy_task can finish, or no-ops immediately if it has already finished without yielding the main task. My original point is that last bit is a very common optimization in languages with async/await since if the future has already resolved, there’s no reason to suspend the current task and pay the switching overhead if the task isn’t blocked waiting for anything. | ||
| ▲ | metaltyphoon an hour ago | parent | prev [-] | |
In C# that Task is ALWAYS hot, aka scheduled to run. | ||