#-----------------------------------------------------------------------------# 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.#-----------------------------------------------------------------------------""" Provide base classes for the Bokeh property system... note:: These classes form part of the very low-level machinery that implements the Bokeh model and property system. It is unlikely that any of these classes or their methods will be applicable to any standard usage or to anyone who is not directly developing on Bokeh's own infrastructure."""#-----------------------------------------------------------------------------# Boilerplate#-----------------------------------------------------------------------------from__future__importannotationsimportlogging# isort:skiplog=logging.getLogger(__name__)#-----------------------------------------------------------------------------# Imports#-----------------------------------------------------------------------------# Standard library importsimporttypesfromcopyimportcopyfromtypingimport(TYPE_CHECKING,Any,Callable,ClassVar,Dict,List,Tuple,Type,TypeVar,Union,)# External importsimportnumpyasnp# Bokeh importsfrom...util.dependenciesimportimport_optionalfrom...util.stringimportnice_joinfrom..has_propsimportHasPropsfrom._sphinximportproperty_link,register_type_link,type_linkfrom.descriptor_factoryimportPropertyDescriptorFactoryfrom.descriptorsimportPropertyDescriptorfrom.singletonsimport(Intrinsic,IntrinsicType,Undefined,UndefinedType,)ifTYPE_CHECKING:from...document.eventsimportDocumentPatchedEventfrom..typesimportID#-----------------------------------------------------------------------------# Globals and constants#-----------------------------------------------------------------------------pd=import_optional('pandas')#-----------------------------------------------------------------------------# General API#-----------------------------------------------------------------------------__all__=('ContainerProperty','DeserializationError','PrimitiveProperty','Property','validation_on',)#-----------------------------------------------------------------------------# Dev API#-----------------------------------------------------------------------------T=TypeVar("T")TypeOrInst=Union[Type[T],T]Init=Union[T,UndefinedType,IntrinsicType]
[docs]classProperty(PropertyDescriptorFactory[T]):""" Base class for Bokeh property instances, which can be added to Bokeh Models. Args: default (obj, optional) : A default value for attributes created from this property to have. help (str or None, optional) : A documentation string for this property. It will be automatically used by the :ref:`bokeh.sphinxext.bokeh_prop` extension when generating Spinx documentation. (default: None) serialized (bool, optional) : Whether attributes created from this property should be included in serialization (default: True) readonly (bool, optional) : Whether attributes created from this property are read-only. (default: False) """# This class attribute is controlled by external helper API for validation_should_validate:ClassVar[bool]=True_readonly:boolalternatives:List[Tuple[Property[Any],Callable[[Property[Any]],T]]]assertions:List[Tuple[Callable[[HasProps,T],bool],str|Callable[[HasProps,str,T],None]]]
[docs]defmake_descriptors(self,name:str)->List[PropertyDescriptor[T]]:""" Return a list of ``PropertyDescriptor`` instances to install on a class, in order to delegate attribute access to this property. Args: name (str) : the name of the property these descriptors are for Returns: list[PropertyDescriptor] The descriptors returned are collected by the ``MetaHasProps`` metaclass and added to ``HasProps`` subclasses during class creation. """return[PropertyDescriptor(name,self)]
def_may_have_unstable_default(self)->bool:""" False if we have a default that is immutable, and will be the same every time (some defaults are generated on demand by a function to be called). """returnisinstance(self._default,types.FunctionType)@classmethoddef_copy_default(cls,default:Callable[[],T]|T)->T:""" Return a copy of the default, or a new value if the default is specified by a function. """ifnotisinstance(default,types.FunctionType):returncopy(default)else:returndefault()def_raw_default(self)->T:""" Return the untransformed default value. The raw_default() needs to be validated and transformed by prepare_value() before use, and may also be replaced later by subclass overrides or by themes. """returnself._copy_default(self._default)
[docs]defthemed_default(self,cls:Type[HasProps],name:str,theme_overrides:Dict[str,Any]|None)->T:""" The default, transformed by prepare_value() and the theme overrides. """overrides=theme_overridesifoverridesisNoneornamenotinoverrides:overrides=cls._overridden_defaults()ifnameinoverrides:default=self._copy_default(overrides[name])else:default=self._raw_default()returnself.prepare_value(cls,name,default)
@propertydefserialized(self)->bool:""" Whether the property should be serialized when serializing an object. This would be False for a "virtual" or "convenience" property that duplicates information already available in other properties, for example. """returnself._serialized@propertydefreadonly(self)->bool:""" Whether this property is read-only. Read-only properties may only be modified by the client (i.e., by BokehJS in the browser). """returnself._readonly
[docs]defmatches(self,new:T,old:T)->bool:""" Whether two parameters match values. If either ``new`` or ``old`` is a NumPy array or Pandas Series or Index, then the result of ``np.array_equal`` will determine if the values match. Otherwise, the result of standard Python equality will be returned. Returns: True, if new and old match, False otherwise """ifisinstance(new,np.ndarray)orisinstance(old,np.ndarray):returnnp.array_equal(new,old)ifpd:ifisinstance(new,pd.Series)orisinstance(old,pd.Series):returnnp.array_equal(new,old)ifisinstance(new,pd.Index)orisinstance(old,pd.Index):returnnp.array_equal(new,old)try:# this handles the special but common case where there is a dict with array# or series as values (e.g. the .data property of a ColumnDataSource)ifisinstance(new,dict)andisinstance(old,dict):ifset(new.keys())!=set(old.keys()):returnFalsereturnall(self.matches(new[k],old[k])forkinnew)# FYI Numpy can erroneously raise a warning about elementwise# comparison here when a timedelta is compared to another scalar.# https://github.com/numpy/numpy/issues/10095returnnew==old# if the comparison fails for some reason, just punt and return no-matchexceptValueError:returnFalse
[docs]deffrom_json(self,json:Any,*,models:Dict[ID,HasProps]|None=None)->T:""" Convert from JSON-compatible values into a value for this property. JSON-compatible values are: list, dict, number, string, bool, None """returnjson
[docs]defserialize_value(self,value:T)->Any:""" Change the value into a JSON serializable format. """returnvalue
[docs]deftransform(self,value:Any)->T:""" Change the value into the canonical format for this property. Args: value (obj) : the value to apply transformation to. Returns: obj: transformed value """returnvalue
[docs]defvalidate(self,value:Any,detail:bool=True)->None:""" Determine whether we can set this property from this value. Validation happens before transform() Args: value (obj) : the value to validate against this property type detail (bool, options) : whether to construct detailed exceptions Generating detailed type validation error messages can be expensive. When doing type checks internally that will not escape exceptions to users, these messages can be skipped by setting this value to False (default: True) Returns: None Raises: ValueError if the value is not valid for this property type """pass
[docs]defis_valid(self,value:Any)->bool:""" Whether the value passes validation Args: value (obj) : the value to validate against this property type Returns: True if valid, False otherwise """try:ifvalidation_on():self.validate(value,False)exceptValueError:returnFalseelse:returnTrue
[docs]defwrap(self,value:T)->T:""" Some property types need to wrap their values in special containers, etc. """returnvalue
def_hinted_value(self,value:Any,hint:DocumentPatchedEvent|None)->Any:returnvaluedefprepare_value(self,owner:HasProps|Type[HasProps],name:str,value:Any,*,hint:DocumentPatchedEvent|None=None)->T:ifvalueisIntrinsic:value=self._raw_default()ifvalueisUndefined:returnvalueerror=Nonetry:ifvalidation_on():hinted_value=self._hinted_value(value,hint)self.validate(hinted_value)exceptValueErrorase:fortp,converterinself.alternatives:iftp.is_valid(value):value=converter(value)breakelse:error=eiferrorisNone:value=self.transform(value)else:obj_repr=ownerifisinstance(owner,HasProps)elseowner.__name__raiseValueError(f"failed to validate {obj_repr}.{name}: {error}")ifisinstance(owner,HasProps):obj=ownerforfn,msg_or_fninself.assertions:ifisinstance(fn,bool):result=fnelse:result=fn(obj,value)assertisinstance(result,bool)ifnotresult:ifisinstance(msg_or_fn,str):raiseValueError(msg_or_fn)else:msg_or_fn(obj,name,value)returnself.wrap(value)@propertydefhas_ref(self)->bool:returnFalse
[docs]defaccepts(self,tp:TypeOrInst[Property[Any]],converter:Callable[[Property[Any]],T])->Property[T]:""" Declare that other types may be converted to this property type. Args: tp (Property) : A type that may be converted automatically to this property type. converter (callable) : A function accepting ``value`` to perform conversion of the value to this property type. Returns: self """tp=ParameterizedProperty._validate_type_param(tp)self.alternatives.append((tp,converter))returnself
[docs]defasserts(self,fn:Callable[[HasProps,T],bool],msg_or_fn:str|Callable[[HasProps,str,T],None])->Property[T]:""" Assert that prepared values satisfy given conditions. Assertions are intended in enforce conditions beyond simple value type validation. For instance, this method can be use to assert that the columns of a ``ColumnDataSource`` all collectively have the same length at all times. Args: fn (callable) : A function accepting ``(obj, value)`` that returns True if the value passes the assertion, or False otherwise. msg_or_fn (str or callable) : A message to print in case the assertion fails, or a function accepting ``(obj, name, value)`` to call in in case the assertion fails. Returns: self """self.assertions.append((fn,msg_or_fn))returnself
TItem=TypeVar("TItem",bound=Property[Any])classParameterizedProperty(Property[TItem]):""" A base class for Properties that have type parameters, e.g. ``List(String)``. """@staticmethoddef_validate_type_param(type_param:TypeOrInst[Property[Any]],*,help_allowed:bool=False)->Property[Any]:ifisinstance(type_param,type):ifissubclass(type_param,Property):returntype_param()else:type_param=type_param.__name__elifisinstance(type_param,Property):iftype_param._helpisnotNoneandnothelp_allowed:raiseValueError("setting 'help' on type parameters doesn't make sense")returntype_paramraiseValueError(f"expected a Property as type parameter, got {type_param}")@propertydeftype_params(self)->List[Property[Any]]:raiseNotImplementedError("abstract method")@propertydefhas_ref(self)->bool:returnany(type_param.has_reffortype_paraminself.type_params)classSingleParameterizedProperty(ParameterizedProperty[T]):""" A parameterized property with a single type parameter. """def__init__(self,type_param:TypeOrInst[Property[Any]],*,default:Init[T]=Intrinsic,help:str|None=None,serialized:bool|None=None,readonly:bool=False):self.type_param=self._validate_type_param(type_param)default=defaultifdefaultisnotIntrinsicelseself.type_param._raw_default()super().__init__(default=default,help=help,serialized=serialized,readonly=readonly)@propertydeftype_params(self)->List[Property[Any]]:return[self.type_param]def__str__(self)->str:returnf"{self.__class__.__name__}({self.type_param})"defvalidate(self,value:Any,detail:bool=True)->None:super().validate(value,detail=detail)self.type_param.validate(value,detail=detail)deffrom_json(self,json:Any,*,models:Dict[str,HasProps]|None=None)->T:returnself.type_param.from_json(json,models=models)deftransform(self,value:T)->T:returnself.type_param.transform(value)defwrap(self,value:T)->T:returnself.type_param.wrap(value)def_may_have_unstable_default(self)->bool:returnself.type_param._may_have_unstable_default()
[docs]classPrimitiveProperty(Property[T]):""" A base class for simple property types. Subclasses should define a class attribute ``_underlying_type`` that is a tuple of acceptable type values for the property. Example: A trivial version of a ``Float`` property might look like: .. code-block:: python class Float(PrimitiveProperty): _underlying_type = (numbers.Real,) """_underlying_type:ClassVar[Tuple[Type[T]]]
[docs]defvalidate(self,value:Any,detail:bool=True)->None:super().validate(value,detail)ifisinstance(value,self._underlying_type):returnifnotdetail:raiseValueError("")expected_type=nice_join([cls.__name__forclsinself._underlying_type])msg=f"expected a value of type {expected_type}, got {value} of type {type(value).__name__}"raiseValueError(msg)
[docs]deffrom_json(self,json:Any,*,models:Dict[str,HasProps]|None=None)->T:ifisinstance(json,self._underlying_type):returnjsonexpected_type=nice_join([cls.__name__forclsinself._underlying_type])msg=f"{self} expected {expected_type}, got {json} of type {type(json).__name__}"raiseDeserializationError(msg)
[docs]classContainerProperty(ParameterizedProperty[T]):""" A base class for Container-like type properties. """def_may_have_unstable_default(self)->bool:# all containers are mutable, so the default can be modifiedreturnTrue
[docs]defvalidation_on()->bool:""" Check if property validation is currently active Returns: bool """returnProperty._should_validate