bun_python
bun_python copied to clipboard
Asyncio Python API - Request For Comment
Would like to add asyncio support to bun_python.
Before I submit the PR, would like to get some thoughts on which API is preferable:
Option A:
import { python, asyncio } from 'bun_python'
const {
say_hello,
} = python.runModule(await Bun.file(path.resolve(import.meta.dir, 'example.py')).text(), 'example.py')
python.run_loop() // returns a promise that resolves when the loop stops
await asyncio(say_hello('world'), timeout_ms)
main().finally(() => python.stop_loop())
Option A has an asyncio() function to wrap Py Coroutines or Py asyncio.Task into an awaitable JS Promise.
Option B:
import { python } from 'bun_python'
const {
say_hello,
} = python.runModule(await Bun.file(path.resolve(import.meta.dir, 'example.py')).text(), 'example.py')
python.run_loop() // returns a promise that resolves when the loop stops
await say_hello('world')
main().finally(() => python.stop_loop())
Option B adds a then() method to all PyObject proxy to make them awaitable.
@codehz
I prefer to choose Option B But I doubt whether this operation will really work... The event loop should block the entire thread, so run_loop should not be able to use promise...
I have a version of it that already works. It depends on python Async functions not monopolizing or holding up the event loop, by not doing any long blocking operations on the main thread, which most python async code today already does.
Also any code in python that is blocking more than a few microseconds, should be wrapped inside asyncio.to_thread(blocking_func). Other wise there will be microstuttering. Also, the GIL lock needs to be released so the thread can use the GIL.
For Option B,
The PyCoro_Check() function in the Python C-API can quickly determine if a given PyObject is a coroutine. The performance characteristics of this function is generally very good because it's implemented as a simple type check.
Shall I go ahead and make a PR based on this? @codehz
seems ok @heri16