#6361·nicegui

Hold the current map and scene in a ContextVar instead of a process-wide class variable

Author: falkoschindlerCreated Sep 29, 2026Updated Sep 29, 2026
Labelsfeature

Description

Layer.current_leaflet and Object3D.current_scene are process-wide class variables. Leaflet.__enter__, Leaflet.__getattribute__ and their Scene twins write them so that a new layer or 3D object finds its map or scene. Since #6345 they hold weak references, so a deleted element is no longer pinned, but the variable is still shared by every task in the process.

scene.box() and m.marker() are safe: the write and the read happen in the same expression. What can go wrong is a Layer or Object3D subclass constructed directly inside a with block, the pattern from the "custom 3D scene objects" documentation, when the block awaits before the construction. While it waits, another client's page handler or a timer may touch its own scene, and the object then lands there:

python
import asyncio
from nicegui import ui
from nicegui.elements.scene.objects.box import Box  # stands in for a custom Object3D subclass

@ui.page('/')
async def page():
    with ui.scene() as scene:
        await asyncio.sleep(1)  # e.g. loading data while another client opens the page
        box = Box()
        ui.label(f'box in own scene: {box.scene is scene}')

ui.run()

Open the page in two tabs within a second. The first tab shows False: its box was registered in the second tab's scene. The same happens with a Layer subclass on ui.leaflet.

Proposal

Option E from #6345: replace the class variable with a contextvars.ContextVar that holds the weak reference. Each task sees its own value, so an await inside a with block cannot be interrupted by another client's write, and nothing is pinned. binding.py and storage.py already use ContextVar. The two constructors keep reading it the same way, so m.marker(...), scene.box() and directly constructed subclasses work as before. This is a behaviour change, which is why it was left out of #6345: a ContextVar is only visible in the task that set it and in tasks spawned from it afterwards. A custom Object3D or Layer subclass constructed directly in an event handler or timer without a surrounding with scene: block works today because the class variable still points at the last scene touched anywhere in the process; with a ContextVar it would fail with the existing assertion instead. scene.box() and m.marker() are unaffected. The change wants a concurrency test along the lines of the example above and a release note for the handler case.

Found while reviewing #6345. ※