#-----------------------------------------------------------------------------# Copyright (c) 2012 - 2022, Anaconda, Inc., and Bokeh Contributors.# All rights reserved.## The full license is in the file LICENSE.txt, distributed with this software.#-----------------------------------------------------------------------------''''''#-----------------------------------------------------------------------------# Boilerplate#-----------------------------------------------------------------------------from__future__importannotationsimportlogging# isort:skiplog=logging.getLogger(__name__)#-----------------------------------------------------------------------------# Imports#-----------------------------------------------------------------------------# Standard library importsimportweakreffromcontextlibimportcontextmanagerfromtypingimportTYPE_CHECKING,Iterator,List# Bokeh importsfrom.stateimportcurstateifTYPE_CHECKING:from..documentimportDocumentfrom..document.lockingimportUnlockedDocumentProxy#-----------------------------------------------------------------------------# Globals and constants#-----------------------------------------------------------------------------__all__=('curdoc','patch_curdoc','set_curdoc',)# annotated global must come first in py 3.7_PATCHED_CURDOCS:List[weakref.ReferenceType[Document|UnlockedDocumentProxy]]=[]#-----------------------------------------------------------------------------# General API#-----------------------------------------------------------------------------
[docs]defcurdoc()->Document|UnlockedDocumentProxy:''' Return the document for the current default state. Returns: Document : the current default document object. '''iflen(_PATCHED_CURDOCS)>0:doc=_PATCHED_CURDOCS[-1]()ifdocisNone:raiseRuntimeError("Patched curdoc has been previously destroyed")returndocreturncurstate().document
#-----------------------------------------------------------------------------# Dev API#-----------------------------------------------------------------------------
[docs]@contextmanagerdefpatch_curdoc(doc:Document|UnlockedDocumentProxy)->Iterator[None]:''' Temporarily override the value of ``curdoc()`` and then return it to its original state. This context manager is useful for controlling the value of ``curdoc()`` while invoking functions (e.g. callbacks). The cont Args: doc (Document) : new Document to use for ``curdoc()`` '''global_PATCHED_CURDOCS_PATCHED_CURDOCS.append(weakref.ref(doc))deldocyield_PATCHED_CURDOCS.pop()
[docs]defset_curdoc(doc:Document)->None:''' Configure the current document (returned by curdoc()). Args: doc (Document) : new Document to use for curdoc() Returns: None .. warning:: Calling this function will replace any existing document. '''curstate().document=doc