#-----------------------------------------------------------------------------# Copyright (c) Anaconda, Inc., and Bokeh Contributors.# All rights reserved.## The full license is in the file LICENSE.txt, distributed with this software.#-----------------------------------------------------------------------------''' Provide a base class for all objects (called Bokeh Models) that can go ina Bokeh |Document|.'''#-----------------------------------------------------------------------------# Boilerplate#-----------------------------------------------------------------------------from__future__importannotationsimportlogging# isort:skiplog=logging.getLogger(__name__)#-----------------------------------------------------------------------------# Imports#-----------------------------------------------------------------------------# Standard library importsfrominspectimportParameter,Signature,isclassfromtypingimportTYPE_CHECKING,Any,Iterable# Bokeh importsfrom..coreimportpropertiesaspfrom..core.has_propsimportHasProps,_default_resolver,abstractfrom..core.property._sphinximporttype_linkfrom..core.property.validationimportwithout_property_validationfrom..core.serializationimportObjectRefRep,Ref,Serializerfrom..core.typesimportIDfrom..eventsimportEventfrom..themesimportdefaultasdefault_themefrom..util.callback_managerimportEventCallbackManager,PropertyCallbackManagerfrom..util.serializationimportmake_idfrom.docsimporthtml_repr,process_examplefrom.utilimport(HasDocumentRef,collect_models,visit_value_and_its_immediate_references,)ifTYPE_CHECKING:fromtyping_extensionsimportSelffrom..core.has_propsimportSetterfrom..core.queryimportSelectorTypefrom..documentimportDocumentfrom..document.eventsimportDocumentPatchedEventfrom..models.callbacksimport(CallbackasJSEventCallback,CustomCodeasJSChangeCallback,)from..util.callback_managerimportPropertyCallback#-----------------------------------------------------------------------------# Globals and constants#-----------------------------------------------------------------------------__all__=('Model',)#-----------------------------------------------------------------------------# General API#-----------------------------------------------------------------------------#-----------------------------------------------------------------------------# Dev API#-----------------------------------------------------------------------------
[docs]@abstractclassModel(HasProps,HasDocumentRef,PropertyCallbackManager,EventCallbackManager):''' Base class for all objects stored in Bokeh |Document| instances. '''# a canonical order for positional args that can be# used for any functions derived from this class_args=()_extra_kws={}@classmethoddef__init_subclass__(cls):super().__init_subclass__()ifcls.__module__.startswith("bokeh.models"):assert"__init__"incls.__dict__,str(cls)parameters=[x[0]forxincls.parameters()]cls.__init__.__signature__=Signature(parameters=parameters)process_example(cls)_id:IDdef__new__(cls,*args:Any,id:ID|None=None,**kwargs:Any)->Self:obj=super().__new__(cls)# Setting 'id' implies deferred initialization, which means properties# will be initialized in a separate step by a deserializer, etc.ifidisnotNone:ifargsorkwargs:raiseValueError("'id' cannot be used together with property initializers")obj._id=idelse:obj._id=make_id()returnobjdef__init__(self,*args:Any,**kwargs:Any)->None:ifargs:raiseValueError("positional arguments are not allowed")if"id"inkwargs:raiseValueError("initializing 'id' is not allowed")super().__init__(**kwargs)default_theme.apply_to_model(self)def__str__(self)->str:name=self.__class__.__name__returnf"{name}(id={self.id!r}, ...)"__repr__=__str__
[docs]defdestroy(self)->None:''' Clean up references to the document and property '''self._document=Noneself._temp_document=Noneself._property_values.clear()
@propertydefid(self)->ID:returnself._idname=p.Nullable(p.String,help=""" An arbitrary, user-supplied name for this model. This name can be useful when querying the document to retrieve specific Bokeh models. .. code:: python >>> plot.scatter([1,2,3], [4,5,6], name="temp") >>> plot.select(name="temp") [GlyphRenderer(id='399d53f5-73e9-44d9-9527-544b761c7705', ...)] .. note:: No uniqueness guarantees or other conditions are enforced on any names that are provided, nor is the name used directly by Bokeh for any reason. """)tags=p.List(p.AnyRef,help=""" An optional list of arbitrary, user-supplied values to attach to this model. This data can be useful when querying the document to retrieve specific Bokeh models: .. code:: python >>> r = plot.scatter([1,2,3], [4,5,6]) >>> r.tags = ["foo", 10] >>> plot.select(tags=['foo', 10]) [GlyphRenderer(id='1de4c3df-a83d-480a-899b-fb263d3d5dd9', ...)] Or simply a convenient way to attach any necessary metadata to a model that can be accessed by ``CustomJS`` callbacks, etc. .. note:: No uniqueness guarantees or other conditions are enforced on any tags that are provided, nor are the tags used directly by Bokeh for any reason. """)js_event_callbacks=p.Dict(p.String,p.List(p.Instance("bokeh.models.callbacks.Callback")),help=""" A mapping of event names to lists of ``CustomJS`` callbacks. Typically, rather then modifying this property directly, callbacks should be added using the ``Model.js_on_event`` method: .. code:: python callback = CustomJS(code="console.log('tap event occurred')") plot.js_on_event('tap', callback) """)js_property_callbacks=p.Dict(p.String,p.List(p.Instance("bokeh.models.callbacks.Callback")),help=""" A mapping of attribute names to lists of ``CustomJS`` callbacks, to be set up on BokehJS side when the document is created. Typically, rather then modifying this property directly, callbacks should be added using the ``Model.js_on_change`` method: .. code:: python callback = CustomJS(code="console.log('stuff')") plot.x_range.js_on_change('start', callback) """)subscribed_events=p.Set(p.String,help=""" Collection of events that are subscribed to by Python callbacks. This is the set of events that will be communicated from BokehJS back to Python for this model. """)syncable:bool=p.Bool(default=True,help=""" Indicates whether this model should be synchronized back to a Bokeh server when updated in a web browser. Setting to ``False`` may be useful to reduce network traffic when dealing with frequently updated objects whose updated values we don't need. .. note:: Setting this property to ``False`` will prevent any ``on_change()`` callbacks on this object from triggering. However, any JS-side callbacks will still work. """)# Properties --------------------------------------------------------------@propertydefref(self)->Ref:returnRef(id=self._id)# Public methods ----------------------------------------------------------
[docs]@classmethoddefclear_extensions(cls)->None:""" Clear any currently defined custom extensions. Serialization calls will result in any currently defined custom extensions being included with the generated Document, whether or not there are utilized. This method can be used to clear out all existing custom extension definitions. """_default_resolver.clear_extensions()
[docs]@classmethod@without_property_validationdefparameters(cls:type[Model])->list[Parameter]:''' Generate Python ``Parameter`` values suitable for functions that are derived from the glyph. Returns: list(Parameter) '''arg_params=[]no_more_defaults=Falseforarginreversed(cls._args):descriptor=cls.lookup(arg)default=descriptor.class_default(cls,no_eval=True)ifdefaultisNone:no_more_defaults=True# simplify field(x) defaults to just present the column nameifisinstance(default,dict)andset(default)=={"field"}:default=default["field"]# make sure built-ins don't hold on to references to actual Modelsifcls.__module__.startswith("bokeh.models"):assertnotisinstance(default,Model)param=Parameter(name=arg,kind=Parameter.POSITIONAL_OR_KEYWORD,# For positional arg properties, default=None means no default.default=Parameter.emptyifno_more_defaultselsedefault,)ifdefault:deldefaulttyp=type_link(descriptor.property)arg_params.insert(0,(param,typ,descriptor.__doc__))# these are not really useful, and should also really be private, just skip themomissions={'js_event_callbacks','js_property_callbacks','subscribed_events'}kwarg_params=[]kws=set(cls.properties())-set(cls._args)-omissionsforkwinkws:descriptor=cls.lookup(kw)default=descriptor.class_default(cls,no_eval=True)# simplify field(x) defaults to just present the column nameifisinstance(default,dict)andset(default)=={"field"}:default=default["field"]# make sure built-ins don't hold on to references to actual Modelsifcls.__module__.startswith("bokeh.models"):assertnotisinstance(default,Model)param=Parameter(name=kw,kind=Parameter.KEYWORD_ONLY,default=default,)deldefaulttyp=type_link(descriptor.property)kwarg_params.append((param,typ,descriptor.__doc__))forkw,(typ,doc)incls._extra_kws.items():param=Parameter(name=kw,kind=Parameter.KEYWORD_ONLY,)kwarg_params.append((param,typ,doc))kwarg_params.sort(key=lambdax:x[0].name)returnarg_params+kwarg_params
defjs_on_event(self,event:str|type[Event],*callbacks:JSEventCallback)->None:ifisinstance(event,str):event_name=Event.cls_for(event).event_nameelifisinstance(event,type)andissubclass(event,Event):event_name=event.event_nameelse:raiseValueError(f"expected string event name or event class, got {event}")all_callbacks=list(self.js_event_callbacks.get(event_name,[]))forcallbackincallbacks:ifcallbacknotinall_callbacks:all_callbacks.append(callback)self.js_event_callbacks[event_name]=all_callbacks
[docs]defjs_link(self,attr:str,other:Model,other_attr:str,attr_selector:int|str|None=None)->None:''' Link two Bokeh model properties using JavaScript. This is a convenience method that simplifies adding a :class:`~bokeh.models.CustomJS` callback to update one Bokeh model property whenever another changes value. Args: attr (str) : The name of a Bokeh property on this model other (Model): A Bokeh model to link to self.attr other_attr (str) : The property on ``other`` to link together attr_selector (int | str) : The index to link an item in a subscriptable ``attr`` Added in version 1.1 Raises: ValueError Examples: This code with ``js_link``: .. code :: python select.js_link('value', plot, 'sizing_mode') is equivalent to the following: .. code:: python from bokeh.models import CustomJS select.js_on_change('value', CustomJS(args=dict(other=plot), code="other.sizing_mode = this.value" ) ) Additionally, to use attr_selector to attach the left side of a range slider to a plot's x_range: .. code :: python range_slider.js_link('value', plot.x_range, 'start', attr_selector=0) which is equivalent to: .. code :: python from bokeh.models import CustomJS range_slider.js_on_change('value', CustomJS(args=dict(other=plot.x_range), code="other.start = this.value[0]" ) ) '''descriptor=self.lookup(attr,raises=False)ifdescriptorisNone:raiseValueError(f"{attr!r} is not a property of self ({self!r})")ifnotisinstance(other,Model):raiseValueError(f"'other' is not a Bokeh model: {other!r}")other_descriptor=other.lookup(other_attr,raises=False)ifother_descriptorisNone:raiseValueError(f"{other_attr!r} is not a property of other ({other!r})")frombokeh.modelsimportCustomJSselector=f"[{attr_selector!r}]"ifattr_selectorisnotNoneelse""cb=CustomJS(args=dict(other=other),code=f"other.{other_descriptor.name} = this.{descriptor.name}{selector}")self.js_on_change(attr,cb)
[docs]defjs_on_change(self,event:str,*callbacks:JSChangeCallback)->None:''' Attach a :class:`~bokeh.models.CustomJS` callback to an arbitrary BokehJS model event. On the BokehJS side, change events for model properties have the form ``"change:property_name"``. As a convenience, if the event name passed to this method is also the name of a property on the model, then it will be prefixed with ``"change:"`` automatically: .. code:: python # these two are equivalent source.js_on_change('data', callback) source.js_on_change('change:data', callback) However, there are other kinds of events that can be useful to respond to, in addition to property change events. For example to run a callback whenever data is streamed to a ``ColumnDataSource``, use the ``"stream"`` event on the source: .. code:: python source.js_on_change('streaming', callback) '''iflen(callbacks)==0:raiseValueError("js_on_change takes an event name and one or more callbacks, got only one parameter")# handle any CustomJS callbacks herefrombokeh.models.callbacksimportCustomCodeifnotall(isinstance(x,CustomCode)forxincallbacks):raiseValueError("not all callback values are CustomCode instances")descriptor=self.lookup(event,raises=False)ifdescriptorisnotNone:event=f"change:{descriptor.name}"old={k:[cbforcbincbs]fork,cbsinself.js_property_callbacks.items()}ifeventnotinself.js_property_callbacks:self.js_property_callbacks[event]=[]forcallbackincallbacks:ifcallbackinself.js_property_callbacks[event]:continueself.js_property_callbacks[event].append(callback)self.trigger('js_property_callbacks',old,self.js_property_callbacks)
[docs]defon_change(self,attr:str,*callbacks:PropertyCallback)->None:''' Add a callback on this object to trigger when ``attr`` changes. Args: attr (str) : an attribute name on this object *callbacks (callable) : callback functions to register Returns: None Examples: .. code-block:: python widget.on_change('value', callback1, callback2, ..., callback_n) '''descriptor=self.lookup(attr)super().on_change(descriptor.name,*callbacks)
[docs]defreferences(self)->set[Model]:''' Returns all ``Models`` that this object has references to. '''returnset(collect_models(self))
[docs]defselect(self,selector:SelectorType)->Iterable[Model]:''' Query this object and all of its references for objects that match the given selector. Args: selector (JSON-like) : Returns: seq[Model] '''from..core.queryimportfindreturnfind(self.references(),selector)
[docs]defselect_one(self,selector:SelectorType)->Model|None:''' Query this object and all of its references for objects that match the given selector. Raises an error if more than one object is found. Returns single matching object, or None if nothing is found Args: selector (JSON-like) : Returns: Model '''result=list(self.select(selector))iflen(result)>1:raiseValueError(f"Found more than one object matching {selector}: {result!r}")iflen(result)==0:returnNonereturnresult[0]
[docs]defset_select(self,selector:type[Model]|SelectorType,updates:dict[str,Any])->None:''' Update objects that match a given selector with the specified attribute/value updates. Args: selector (JSON-like) : updates (dict) : Returns: None '''ifisclass(selector)andissubclass(selector,Model):selector=dict(type=selector)forobjinself.select(selector):forkey,valinupdates.items():setattr(obj,key,val)
[docs]deftrigger(self,attr:str,old:Any,new:Any,hint:DocumentPatchedEvent|None=None,setter:Setter|None=None)->None:''' '''# The explicit assumption here is that hinted events do not need to# go through all the same invalidation steps. Currently this is the# case for ColumnsStreamedEvent and ColumnsPatchedEvent. However,# this may need to be further refined in the future, if the# assumption does not hold for future hinted events (e.g. the hint# could specify explicitly whether to do normal invalidation or not)ifhintisNone:dirty_count=0defmark_dirty(_:HasProps):nonlocaldirty_countdirty_count+=1ifself._documentisnotNone:visit_value_and_its_immediate_references(new,mark_dirty)visit_value_and_its_immediate_references(old,mark_dirty)ifdirty_count>0:self.document.models.invalidate()# chain up to invoke callbacksdescriptor=self.lookup(attr)super().trigger(descriptor.name,old,new,hint=hint,setter=setter)
def_attach_document(self,doc:Document)->None:''' Attach a model to a Bokeh |Document|. This private interface should only ever called by the Document implementation to set the private ._document field properly '''ifself.documentisdoc:# nothing to doreturnifself.documentisnotNone:raiseRuntimeError(f"Models must be owned by only a single document, {self!r} is already in a doc")doc.theme.apply_to_model(self)self.document=docself._update_event_callbacks()def_detach_document(self)->None:''' Detach a model from a Bokeh |Document|. This private interface should only ever called by the Document implementation to unset the private ._document field properly '''self.document=Nonedefault_theme.apply_to_model(self)def_repr_html_(self)->str:returnhtml_repr(self)def_sphinx_height_hint(self)->int|None:returnNone