function set_curdoc
A context manager that temporarily sets the current Bokeh document (curdoc) in the application state, ensuring it is properly cleaned up after use.
/tf/active/vicechatdev/patches/server.py
394 - 397
simple
Purpose
This function is used to temporarily establish a Bokeh document as the current document in Panel's state management system. It's essential for managing document context in Panel applications, particularly when dealing with multiple documents or when needing to ensure proper document lifecycle management. The context manager pattern ensures that the document reference is always cleaned up, even if an exception occurs.
Source Code
def set_curdoc(doc):
state.curdoc = doc
yield
state.curdoc = None
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
doc |
- | - | positional_or_keyword |
Parameter Details
doc: A Bokeh Document object that should be set as the current document. This is typically a bokeh.document.Document instance that represents the current application's document context. The document contains all the models, callbacks, and state for a Panel/Bokeh application session.
Return Value
As a context manager (decorated with @contextmanager), this function yields control back to the caller after setting state.curdoc to the provided document. It doesn't return a specific value but allows code to execute within the context where the document is active. After the context exits, state.curdoc is reset to None.
Dependencies
bokehparam
Required Imports
from contextlib import contextmanager
from state import state
Usage Example
from bokeh.document import Document
from contextlib import contextmanager
from state import state
# Assuming state object is available
doc = Document()
# Use the context manager to temporarily set the current document
with set_curdoc(doc):
# Within this block, state.curdoc is set to doc
print(f"Current doc: {state.curdoc}")
# Perform operations that require the document context
# Add models, callbacks, etc.
# After exiting the context, state.curdoc is None
print(f"After context: {state.curdoc}") # Will print None
Best Practices
- Always use this as a context manager (with statement) to ensure proper cleanup of the document reference
- Do not manually set state.curdoc outside of this context manager to maintain consistency
- Ensure the document object passed is a valid Bokeh Document instance
- Be aware that nested calls to set_curdoc will overwrite the previous document reference
- This is typically used internally by Panel's server infrastructure and should be used carefully in custom code
- The function ensures thread-safety by managing document state at the application level
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function unlocked 67.9% similar
-
function init_doc 64.7% similar
-
function modify_document 60.2% similar
-
function _eval_panel 54.7% similar
-
class Application 54.4% similar