Update nest-asyncio/README.md

This commit is contained in:
2025-03-01 14:52:43 +00:00
parent 95f1476958
commit 3e2d74afcd

View File

@@ -1,15 +1,31 @@
```python
def sync(obj):
import asyncio, nest_asyncio; nest_asyncio.apply()
if asyncio.iscoroutine(obj): return asyncio.run(obj)
if asyncio.iscoroutinefunction(func := obj):
return lambda *args, **kwargs: sync(func(*args, **kwargs))
import asyncio, functools
if asyncio.iscoroutine(coro := obj):
loop, future = asyncio.get_event_loop(), asyncio.ensure_future(coro)
while not future.done():
loop._process_events(loop._selector.select(0))
if (ready := loop._ready) and not (handle := ready.popleft())._cancelled:
task = (tasks := asyncio.tasks._current_tasks).pop(loop, None)
handle._run()
tasks[loop] = task
return future.result()
if asyncio.iscoroutinefunction(func := obj): return functools.wraps(func)(
lambda *args, **kwargs: sync(func(*args, **kwargs)))
for attr in dir(obj):
if asyncio.iscoroutinefunction(method := getattr(obj, attr)):
setattr(obj, attr, sync(method))
return obj
async def foo(): return 42
sync(foo()), sync(foo)()
print(sync(foo()), sync(foo)())
from playwright.async_api import async_playwright
browser = sync(sync(async_playwright().start()).firefox.launch())
page = sync(sync(browser.new_page()))
page._repr_png_ = page.screenshot
page.goto('https://naver.com')
page
```
```python