bokeh.core.properties#
In order to streamline and automate the creation and use of models that can be used for describing plots and scenes, Bokeh provides a collection of properties and property mixins. Property classes provide automatic validation and serialization for a large collection of useful types. Mixin and container classes provide for easy bulk addition of properties to model classes.
Provide property types for Bokeh models
Properties are objects that can be assigned as class attributes on Bokeh models, to provide automatic serialization, validation, and documentation.
This documentation is broken down into the following sections:
Overview#
There are many property types defined in the module, for example Int
to
represent integral values, Seq
to represent sequences (e.g. lists or
tuples, etc.). Properties can also be combined: Seq(Float)
represents
a sequence of floating point values.
For example, the following defines a model that has integer, string, and list[float] properties:
class SomeModel(Model):
foo = Int
bar = String(default="something")
baz = List(Float, help="docs for baz prop")
As seen, properties can be declared as just the property type, e.g.
foo = Int
, in which case the properties are automatically instantiated
on new Model objects. Or the property can be instantiated on the class,
and configured with default values and help strings.
The properties of this class can be initialized by specifying keyword arguments to the initializer:
m = SomeModel(foo=10, bar="a str", baz=[1,2,3,4])
But also by setting the attributes on an instance:
m.foo = 20
Attempts to set a property to a value of the wrong type will
result in a ValueError
exception:
>>> m.foo = 2.3
Traceback (most recent call last):
<< traceback omitted >>
ValueError: expected a value of type Integral, got 2.3 of type float
Models with properties know how to serialize themselves, to be understood by BokehJS. Additionally, any help strings provided on properties can be easily and automatically extracted with the Sphinx extensions in the bokeh.sphinxext module.
Basic Properties#
- class Angle(default: Init[float] = 0.0, *, help: str | None = None)[source]#
Accept floating point angle values.
Angle
is equivalent toFloat
but is provided for cases when it is more semantically meaningful.- Parameters:
default (float, 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 bokeh_prop extension when generating Spinx documentation. (default: None)
- class Any(default: Init[Any] = None, help: str | None = None)[source]#
Accept all values.
The
Any
property does not do any validation or transformation.- Parameters:
default (obj or None, optional) – A default value for attributes created from this property to have (default: None)
help (str or None, optional) – A documentation string for this property. It will be automatically used by the bokeh_prop extension when generating Spinx documentation. (default: None)
Example
>>> class AnyModel(HasProps): ... prop = Any() ... >>> m = AnyModel() >>> m.prop = True >>> m.prop = 10 >>> m.prop = 3.14 >>> m.prop = "foo" >>> m.prop = [1, 2, 3]
- class AnyRef(default: Init[Any] = None, help: str | None = None)[source]#
Accept all values and force reference discovery.
- class Auto[source]#
Accepts only the string “auto”.
Useful for properties that can be configured to behave “automatically”.
Example
This property is often most useful in conjunction with the
Either
property.>>> class AutoModel(HasProps): ... prop = Either(Float, Auto) ... >>> m = AutoModel() >>> m.prop = 10.2 >>> m.prop = "auto" >>> m.prop = "foo" # ValueError !! >>> m.prop = [1, 2, 3] # ValueError !!
- class Bool(default: Init[bool] = False, *, help: str | None = None)[source]#
Accept boolean values.
- Parameters:
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 bokeh_prop extension when generating Spinx documentation. (default: None)
Example
>>> class BoolModel(HasProps): ... prop = Bool(default=False) ... >>> m = BoolModel() >>> m.prop = True >>> m.prop = False >>> m.prop = 10 # ValueError !!
- class Byte(default: Init[int] = 0, help: str | None = None)[source]#
Accept integral byte values (0-255).
Example
>>> class ByteModel(HasProps): ... prop = Byte(default=0) ... >>> m = ByteModel() >>> m.prop = 255 >>> m.prop = 256 # ValueError !! >>> m.prop = 10.3 # ValueError !!
- class Color(default: Init[str | tuple[int, int, int] | tuple[int, int, int, float]] = Undefined, *, help: str | None = None)[source]#
Accept color values in a variety of ways.
If a color is provided as a string, Bokeh determines whether this string represents one of the named CSS colors (such as “red”), a CSS4 color string (such as “rgb(0, 200, 0)”), or a hex value (such as “#00FF00”).
If a 3-tuple is provided, it is treated as RGB values (between 0 and 255).
If a 4-tuple is provided, it is treated as RGBA values (between 0 and 255 for RGB and alpha as a float between 0 and 1).
If a 32-bit unsigned integer is provided, it is treated as RGBA values in a 0xRRGGBBAA byte order pattern.
Example
>>> class ColorModel(HasProps): ... prop = Color() ... >>> m = ColorModel() >>> m.prop = "firebrick" >>> m.prop = "#a240a2" >>> m.prop = (100, 100, 255) >>> m.prop = (100, 100, 255, 0.5) >>> m.prop = "junk" # ValueError !! >>> m.prop = (100.2, 57.3, 10.2) # ValueError !!
- class Complex(default: Init[complex] = 0j, *, help: str | None = None)[source]#
Accept complex floating point values.
- Parameters:
default (complex, 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 bokeh_prop extension when generating Spinx documentation. (default: None)
- CoordinateLike#
alias of Either(Float, Datetime, Factor(Either(String, Tuple(String, String), Tuple(String, String, String))))
- class DashPattern(default=[], *, help: str | None = None)[source]#
Accept line dash specifications.
Express patterns that describe line dashes.
DashPattern
values can be specified in a variety of ways:An enum: “solid”, “dashed”, “dotted”, “dotdash”, “dashdot”
a tuple or list of integers in the HTML5 Canvas dash specification style. Note that if the list of integers has an odd number of elements, then it is duplicated, and that duplicated list becomes the new dash list.
To indicate that dashing is turned off (solid lines), specify the empty list [].
- class Date(*, default: Init[T] = Intrinsic, help: str | None = None)[source]#
Accept ISO format Date (but not DateTime) values.
- class Datetime(default: Init[str | datetime.date | datetime.datetime] = Undefined, *, help: str | None = None)[source]#
Accept ISO format Datetime values.
- class Either(type_param0: TypeOrInst[Property[Any]], *type_params: TypeOrInst[Property[Any]], default: Init[T] = Intrinsic, help: str | None = None)[source]#
Accept values according to a sequence of other property types.
Example:
>>> class EitherModel(HasProps): ... prop = Either(Bool, Int, Auto) ... >>> m = EitherModel() >>> m.prop = True >>> m.prop = 10 >>> m.prop = "auto" >>> m.prop = 10.3 # ValueError !! >>> m.prop = "foo" # ValueError !!
- class Enum(enum: Enumeration, *, default: Union[str, UndefinedType, IntrinsicType] = ..., help: str | None = ...)[source]#
- class Enum(enum: str, *values: str, default: Union[str, UndefinedType, IntrinsicType] = ..., help: str | None = ...)
Accept values from enumerations.
The first value in enumeration is used as the default value, unless the
default
keyword argument is used.See bokeh.core.enums for more information.
- class Float(default: Init[float] = 0.0, *, help: str | None = None)[source]#
Accept floating point values.
- Parameters:
default (float, 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 bokeh_prop extension when generating Spinx documentation. (default: None)
Example
>>> class FloatModel(HasProps): ... prop = Float() ... >>> m = FloatModel() >>> m.prop = 10 >>> m.prop = 10.3 >>> m.prop = "foo" # ValueError !!
- class Image(*, default: Init[T] = Intrinsic, help: str | None = None)[source]#
Accept image file types, e.g PNG, JPEG, TIFF, etc.
This property can be configured with:
A
pathlib.Path
image file pathA data URL encoded image string
A string filename to be loaded with
PIL.Image.open
An RGB(A) NumPy array, will be converted to PNG
A
PIL.Image.Image
object
In all cases, the image data is serialized as a Base64 encoded string.
- class Int(default: Init[int] = 0, *, help: str | None = None)[source]#
Accept signed integer values.
- Parameters:
default (int, 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 bokeh_prop extension when generating Spinx documentation. (default: None)
Example
>>> class IntModel(HasProps): ... prop = Int() ... >>> m = IntModel() >>> m.prop = 10 >>> m.prop = -200 >>> m.prop = 10.3 # ValueError !!
- class Interval(type_param: TypeOrInst[Property[T]], start: T, end: T, *, default: Init[T] = Undefined, help: str | None = None)[source]#
Accept numeric values that are contained within a given interval.
- Parameters:
interval_type (numeric property) – numeric types for the range, e.g.
Int
,Float
start (number) – A minimum allowable value for the range. Values less than
start
will result in validation errors.end (number) – A maximum allowable value for the range. Values greater than
end
will result in validation errors.
Example
>>> class RangeModel(HasProps): ... prop = Range(Float, 10, 20) ... >>> m = RangeModel() >>> m.prop = 10 >>> m.prop = 20 >>> m.prop = 15 >>> m.prop = 2 # ValueError !! >>> m.prop = 22 # ValueError !! >>> m.prop = "foo" # ValueError !!
- class JSON(default: Init[str] = '', *, help: str | None = None)[source]#
Accept JSON string values.
The value is transmitted and received by BokehJS as a string containing JSON content. i.e., you must use
JSON.parse
to unpack the value into a JavaScript hash.- Parameters:
default (string, 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 bokeh_prop extension when generating Spinx documentation. (default: None)
- class MinMaxBounds(default='auto', *, accept_datetime: bool = False, help: str | None = None)[source]#
Accept (min, max) bounds tuples for use with Ranges.
Bounds are provided as a tuple of
(min, max)
so regardless of whether your range is increasing or decreasing, the first item should be the minimum value of the range and the second item should be the maximum. Setting min > max will result in aValueError
.Setting bounds to None will allow your plot to pan/zoom as far as you want. If you only want to constrain one end of the plot, you can set min or max to
None
e.g.DataRange1d(bounds=(None, 12))
- class NonNegative(type_param: TypeOrInst[Property[T]], *, default: Init[T] = Intrinsic, help: str | None = None)[source]#
A property accepting a value of some other type while having undefined default.
- class NonNegativeInt(default: Init[int] = Intrinsic, *, help: str | None = None)[source]#
Accept non-negative integers.
Deprecated since version 3.0.0: Use
NonNegative(Int)
instead.
- class Nothing(*, help: str | None = None)[source]#
The bottom type of bokeh’s type system. It doesn’t accept any values.
- class Null(default: Init[None] = None, *, help: str | None = None)[source]#
Accept only
None
value.Use this in conjunction with
Either(Null, Type)
or asNullable(Type)
.
- class Percent(default: Init[float] = 0.0, *, help: str | None = None)[source]#
Accept floating point percentage values.
Percent
can be useful and semantically meaningful for specifying things like alpha values and extents.- Parameters:
default (float, 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 bokeh_prop extension when generating Spinx documentation. (default: None)
Example
>>> class PercentModel(HasProps): ... prop = Percent() ... >>> m = PercentModel() >>> m.prop = 0.0 >>> m.prop = 0.2 >>> m.prop = 1.0 >>> m.prop = -2 # ValueError !! >>> m.prop = 5 # ValueError !!
- class Positive(type_param: TypeOrInst[Property[T]], *, default: Init[T] = Intrinsic, help: str | None = None)[source]#
A property accepting a value of some other type while having undefined default.
- class PositiveInt(default: Init[int] = Intrinsic, *, help: str | None = None)[source]#
Accept positive integers.
Deprecated since version 3.0.0: Use
Positive(Int)
instead.
- class RGB(*, default: Init[T] = Intrinsic, help: str | None = None)[source]#
Accept colors.RGB values.
- class Regex(regex: str, *, default: Init[str] = Undefined, help: str | None = None)[source]#
Accept strings that match a given regular expression.
- Parameters:
default (string, 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 bokeh_prop extension when generating Spinx documentation. (default: None)
Example
>>> class RegexModel(HasProps): ... prop = Regex("foo[0-9]+bar") ... >>> m = RegexModel() >>> m.prop = "foo123bar" >>> m.prop = "foo" # ValueError !! >>> m.prop = [1, 2, 3] # ValueError !!
- class Size(default: Init[float] = 0.0, *, help: str | None = None)[source]#
Accept non-negative numeric values.
- Parameters:
default (float, 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 bokeh_prop extension when generating Spinx documentation. (default: None)
Example
>>> class SizeModel(HasProps): ... prop = Size() ... >>> m = SizeModel() >>> m.prop = 0 >>> m.prop = 10e6 >>> m.prop = -10 # ValueError !! >>> m.prop = "foo" # ValueError !!
- class String(default: Init[str] = '', *, help: str | None = None)[source]#
Accept string values.
- Parameters:
default (string, 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 bokeh_prop extension when generating Spinx documentation. (default: None)
Example
>>> class StringModel(HasProps): ... prop = String() ... >>> m = StringModel() >>> m.prop = "foo" >>> m.prop = 10.3 # ValueError !! >>> m.prop = [1, 2, 3] # ValueError !!
- class Time(default: Init[str | datetime.time] = Undefined, *, help: str | None = None)[source]#
Accept ISO format time values.
- class TimeDelta(default: Init[datetime.timedelta] = datetime.timedelta(0), *, help: str | None = None)[source]#
Accept TimeDelta values.
Container Properties#
- class Array(item_type: TypeOrInst[Property[T]], *, default: Init[T] = Undefined, help: str | None = None)[source]#
Accept NumPy array values.
- class ColumnData(keys_type: TypeOrInst[Property[Any]], values_type: TypeOrInst[Property[Any]], *, default: Init[T] = {}, help: str | None = None)[source]#
Accept a Python dictionary suitable as the
data
attribute of aColumnDataSource
.This class is a specialization of
Dict
that handles efficiently encoding columns that are NumPy arrays.
- class Dict(keys_type: TypeOrInst[Property[Any]], values_type: TypeOrInst[Property[Any]], *, default: Init[T] = {}, help: str | None = None)[source]#
Accept Python dict values.
If a default value is passed in, then a shallow copy of it will be used for each new use of this property.
- class List(item_type: TypeOrInst[Property[T]], *, default: Init[T] = [], help: str | None = None)[source]#
Accept Python list values.
- class RelativeDelta(default={}, *, help: str | None = None)[source]#
Accept RelativeDelta dicts for time delta values.
- class Seq(item_type: TypeOrInst[Property[T]], *, default: Init[T] = Undefined, help: str | None = None)[source]#
Accept non-string ordered sequences of values, e.g. list, tuple, array.
- class Set(item_type: TypeOrInst[Property[T]], *, default: Init[T] = {}, help: str | None = None)[source]#
Accept Python
set()
values.
DataSpec Properties#
- class AngleSpec(default=Undefined, units_default='rad', *, help: str | None = None)[source]#
A
DataSpec
property that accepts numeric fixed values, and also provides an associated units property to store angle units.Acceptable values for units are
"deg"
,"rad"
,"grad"
and"turn"
.
- class ColorSpec(default, *, help: str | None = None)[source]#
A
DataSpec
property that acceptsColor
fixed values.The
ColorSpec
property attempts to first interpret string values as colors. Otherwise, string values are interpreted as field names. For example:m.color = "#a4225f" # value (hex color string) m.color = "firebrick" # value (named CSS color string) m.color = "foo" # field (named "foo")
This automatic interpretation can be override using the dict format directly, or by using the
field()
function:m.color = { "field": "firebrick" } # field (named "firebrick") m.color = field("firebrick") # field (named "firebrick")
- class DataSpec(value_type, default, *, help: str | None = None)[source]#
Base class for properties that accept either a fixed value, or a string name that references a column in a
ColumnDataSource
.Many Bokeh models have properties that a user might want to set either to a single fixed value, or to have the property take values from some column in a data source. As a concrete example consider a glyph with an
x
property for location. We might want to set all the glyphs that get drawn to have the same location, sayx=10
. It would be convenient to just be able to write:glyph.x = 10
Alternatively, maybe the each glyph that gets drawn should have a different location, according to the “pressure” column of a data source. In this case we would like to be able to write:
glyph.x = "pressure"
Bokeh
DataSpec
properties (and subclasses) afford this ease of and consistency of expression. Ultimately, allDataSpec
properties resolve to dictionary values, with either a"value"
key, or a"field"
key, depending on how it is set.For instance:
glyph.x = 10 # => { 'value': 10 } glyph.x = "pressure" # => { 'field': 'pressure' }
When these underlying dictionary dictionary values are received in the browser, BokehJS knows how to interpret them and take the correct, expected action (i.e., draw the glyph at
x=10
, or draw the glyph withx
coordinates from the “pressure” column). In this way, both use-cases may be expressed easily in python, without having to handle anything differently, from the user perspective.It is worth noting that
DataSpec
properties can also be set directly with properly formed dictionary values:glyph.x = { 'value': 10 } # same as glyph.x = 10 glyph.x = { 'field': 'pressure' } # same as glyph.x = "pressure"
Setting the property directly as a dict can be useful in certain situations. For instance some
DataSpec
subclasses also add a"units"
key to the dictionary. This key is often set automatically, but the dictionary format provides a direct mechanism to override as necessary. Additionally,DataSpec
can have a"transform"
key, that specifies a client-side transform that should be applied to any fixed or field values before they are uses. As an example, you might want to apply aJitter
transform to thex
values:glyph.x = { 'value': 10, 'transform': Jitter(width=0.4) }
Note that
DataSpec
is not normally useful on its own. Typically, a model will define properties using one of the subclasses such asNumberSpec
orColorSpec
. For example, a Bokeh model withx
,y
andcolor
properties that can handle fixed values or columns automatically might look like:class SomeModel(Model): x = NumberSpec(default=0, help="docs for x") y = NumberSpec(default=0, help="docs for y") color = ColorSpec(help="docs for color") # defaults to None
- class DistanceSpec(default=Undefined, units_default='data', *, help: str | None = None)[source]#
A
DataSpec
property that accepts numeric fixed values or strings that refer to columns in aColumnDataSource
, and also provides an associated units property to store units information. Acceptable values for units are"screen"
and"data"
.
- class FontSizeSpec(default, *, help: str | None = None)[source]#
A
DataSpec
property that accepts font-size fixed values.The
FontSizeSpec
property attempts to first interpret string values as font sizes (i.e. valid CSS length values). Otherwise string values are interpreted as field names. For example:m.font_size = "13px" # value m.font_size = "1.5em" # value m.font_size = "foo" # field
A full list of all valid CSS length units can be found here:
- class MarkerSpec(default, *, help: str | None = None)[source]#
A
DataSpec
property that accepts marker types as fixed values.The
MarkerSpec
property attempts to first interpret string values as marker types. Otherwise string values are interpreted as field names. For example:m.font_size = "circle" # value m.font_size = "square" # value m.font_size = "foo" # field
- class NumberSpec(default=Undefined, *, help: str | None = None, accept_datetime=True, accept_timedelta=True)[source]#
A
DataSpec
property that accepts numeric and datetime fixed values.By default, date and datetime values are immediately converted to milliseconds since epoch. It is possible to disable processing of datetime values by passing
accept_datetime=False
.By default, timedelta values are immediately converted to absolute milliseconds. It is possible to disable processing of timedelta values by passing
accept_timedelta=False
Timedelta values are interpreted as absolute milliseconds.
m.location = 10.3 # value m.location = "foo" # field
- class SizeSpec(default=Undefined, *, help: str | None = None, accept_datetime=True, accept_timedelta=True)[source]#
A
DataSpec
property that accepts non-negative numeric fixed values for size values or strings that refer to columns in aColumnDataSource
.
- class StringSpec(default, *, help: str | None = None)[source]#
A
DataSpec
property that accepts string fixed values.Because acceptable fixed values and field names are both strings, it can be necessary explicitly to disambiguate these possibilities. By default, string values are interpreted as fields, but the
value()
function can be used to specify that a string should interpreted as a value:m.title = value("foo") # value m.title = "foo" # field
- class UnitsSpec(default, units_enum, units_default, *, help: str | None = None)[source]#
A
DataSpec
property that accepts numeric fixed values, and also provides an associated units property to store units information.
Helpers#
- expr(expr: Expression, transform: NotRequired[Transform] = Unspecified, units: NotRequired[str] = Unspecified) None #
Expr(expr: ‘Expression’, transform: ‘NotRequired[Transform]’ = Unspecified, units: ‘NotRequired[str]’ = Unspecified)
Special Properties#
- class Instance(instance_type: type[T] | Callable[[], type[T]] | str, default: Init[T] = Undefined, help: str | None = None)[source]#
Accept values that are instances of serializable types (e.g.
HasProps
).
- class InstanceDefault(model: type[I], **kwargs: Any)[source]#
Provide a deferred initializer for Instance defaults.
This is useful for Bokeh models with Instance properties that should have unique default values for every model instance. Using an InstanceDefault will afford better user-facing documentation than a lambda initializer.
- class Include(delegate: type[HasProps], *, help: str = '', prefix: str | None = None)[source]#
Include “mix-in” property collection in a Bokeh model.
See bokeh.core.property_mixins for more details.
- class Nullable(type_param: TypeOrInst[Property[T]], *, default: Init[T | None] = None, help: str | None = None)[source]#
A property accepting
None
or a value of some other type.
- class NonNullable(type_param: TypeOrInst[Property[T]], *, default: Init[T] = Undefined, help: str | None = None)[source]#
A property accepting a value of some other type while having undefined default.
Deprecated since version 3.0.0: Use
bokeh.core.property.required.Required
instead.
- class NotSerialized(type_param: TypeOrInst[Property[T]], *, default: Init[T] = Intrinsic, help: str | None = None)[source]#
A property which state won’t be synced with the browser.
- class Object(instance_type: type[T] | Callable[[], type[T]] | str, default: Init[T] = Undefined, help: str | None = None)[source]#
Accept values that are instances of any class.
Note
This is primarily useful for validation purpose. Non-serializable objects will fail regardless during the serialization process.
- class Override(*, default: T)[source]#
Override attributes of Bokeh property in derived Models.
When subclassing a Bokeh Model, it may be desirable to change some of the attributes of the property itself, from those on the base class. This is accomplished using the
Override
class.Currently,
Override
can only be use to override thedefault
value for the property.- Keyword Arguments:
default (obj) – a default value for this property on a subclass
Example
Consider the following class definitions:
from bokeh.model import Model from bokeh.properties import Int, Override class Parent(Model): foo = Int(default=10) class Child(Parent): foo = Override(default=20)
The parent class has an integer property
foo
with default value 10. The child class uses the following code:foo = Override(default=20)
to specify that the default value for the
foo
property should be 20 on instances of the child class:>>> p = Parent() >>> p.foo 10 >>> c = Child() >>> c.foo 20
Validation-only Properties#
Validation Control#
By default, Bokeh properties perform type validation on values. This helps to ensure the consistency of any data exchanged between Python and JavaScript, as well as provide detailed and immediate feedback to users if they attempt to set values of the wrong type. However, these type checks incur some overhead. In some cases it may be desirable to turn off validation in specific places, or even entirely, in order to boost performance. The following API is available to control when type validation occurs.
- class validate(value)[source]#
Control validation of bokeh properties
This can be used as a context manager, or as a normal callable
- Parameters:
value (bool) – Whether validation should occur or not
Example
with validate(False): # do no validate while within this block pass validate(False) # don't validate ever
See also
validation_on()
: check the state of validationwithout_property_validation()
: function decorator