Introduction to Async Python
Modern web applications in javascript runs in a single thread, but they are able to concurrently handle a number of user interactions. This is enabled by the async/await syntax that yields control to the event loop. We chose async Python for vuer to enable highly-performant, two-way event-driven communication between the frontend and Python server. In contrast, viser uses a synchronous API that hides communication implicitly, which can cause freezing when rendering many geometries. Async patterns let you explicitly handle concurrency in a cooperative manner for better performance.
The downside, however, is that async python will be a little different from what you are used to, so we prepared this short tutorial to teach you the basics. For a canonical introduction to async programming, see async-io documentation.
Understanding The Event Loop
The event loop is the heart of async programming. Here's how it works:
Here's a simple example showing two tasks running concurrently:
Output:
What the event loop does:
- Starts
task_a()→ prints "A: start" → hitsawait sleep(0.5)→ pauses - Starts
task_b()→ prints "B: start" → hitsawait sleep(0.3)→ pauses - After 0.3s: resumes
task_b()→ prints "B: done" - After 0.5s: resumes
task_a()→ prints "A: done"
Both tasks run concurrently, interleaving their execution through the event loop.
Canceling Tasks
Use task.cancel() to stop long-running tasks:
Output:
Async in Vuer
In Vuer, use sess.spawn_task() just like asyncio.create_task():
Output:
This pattern lets you handle user interactions, sensors, and animations concurrently in Vuer.
Now you know the basics of async programming in Vuer, let's move on to setting up your first 3D scene!