bokeh.core.properties¶
In order to streamline and automate the creation and use of models that can 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=None, help=None, serialized=True, readonly=False)[source]¶ Accept floating point angle values.
Angle
is equivalent toFloat
but is provided for cases when it is more semantically meaningful.Parameters: - default (float 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)
- 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)
-
class
Any
(default=None, help=None, serialized=True, readonly=False)[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)
- 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)
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=None, help=None, serialized=True, readonly=False)[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=None, help=None, serialized=True, readonly=False)[source]¶ Accept boolean values.
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)
- 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)
Example
>>> class BoolModel(HasProps): ... prop = Bool(default=False) ... >>> m = BoolModel() >>> m.prop = True >>> m.prop = False >>> m.prop = 10 # ValueError !!
-
class
Byte
(default=0, help=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=None, help=None)[source]¶ Accept color values in a variety of ways.
For colors, because we support named colors and hex values prefaced with a “#”, when we are handed a string value, there is a little interpretation: if the value is one of the 147 SVG named colors or it starts with a “#”, then it is interpreted as a value.
If a 3-tuple is provided, then it is treated as an RGB (0..255). If a 4-tuple is provided, then it is treated as an RGBa (0..255), with alpha as a float between 0 and 1. (This follows the HTML5 Canvas API.)
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=None, help=None, serialized=True, readonly=False)[source]¶ Accept complex floating point values.
Parameters: - default (complex 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)
- 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)
-
class
DashPattern
(default=[], help=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
Either
(tp1, tp2, *type_params, **kwargs)[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, *values, **kwargs)[source]¶ 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=None, help=None, serialized=True, readonly=False)[source]¶ Accept floating point values.
Parameters: - default (float 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)
- 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)
Example
>>> class FloatModel(HasProps): ... prop = Float() ... >>> m = FloatModel() >>> m.prop = 10 >>> m.prop = 10.3 >>> m.prop = "foo" # ValueError !!
-
class
Image
(default=None, help=None, serialized=True, readonly=False)[source]¶ Accept image file types, e.g PNG, JPEG, TIFF, etc.
This property can be configured with:
- 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.
- A string filename to be loaded with
-
class
Instance
(instance_type, default=None, help=None)[source]¶ Accept values that are instances of
HasProps
.
-
class
Int
(default=None, help=None, serialized=True, readonly=False)[source]¶ Accept signed integer values.
Parameters: - default (int 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)
- 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)
Example
>>> class IntModel(HasProps): ... prop = Int() ... >>> m = IntModel() >>> m.prop = 10 >>> m.prop = -200 >>> m.prop = 10.3 # ValueError !!
-
class
Interval
(interval_type, start, end, default=None, help=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 !!
- interval_type (numeric property) – numeric types for the range, e.g.
-
class
JSON
(default=None, help=None, serialized=True, readonly=False)[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 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)
- 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)
-
class
MinMaxBounds
(accept_datetime=False, default='auto', help=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
Percent
(default=None, help=None, serialized=True, readonly=False)[source]¶ Accept floating point percentage values.
Percent
can be useful and semantically meaningful for specifying things like alpha values and extents.Parameters: - default (float 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)
- 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)
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
RGB
(default=None, help=None, serialized=True, readonly=False)[source]¶ Accept colors.RGB values.
-
class
Regex
(regex, default=None, help=None)[source]¶ Accept strings that match a given regular expression.
Parameters: - default (string 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)
- 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)
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=None, help=None, serialized=True, readonly=False)[source]¶ Accept non-negative numeric values.
Parameters: - default (float 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)
- 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)
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=None, help=None, serialized=True, readonly=False)[source]¶ Accept string values.
Parameters: - default (string 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)
- 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)
Example
>>> class StringModel(HasProps): ... prop = String() ... >>> m = StringModel() >>> m.prop = "foo" >>> m.prop = 10.3 # ValueError !! >>> m.prop = [1, 2, 3] # ValueError !!
Container Properties¶
-
class
ColumnData
(keys_type, values_type, default={}, help=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, values_type, default={}, help=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
RelativeDelta
(default={}, help=None)[source]¶ Accept RelativeDelta dicts for time delta values.
DataSpec Properties¶
-
class
AngleSpec
(default=None, units_default='rad', help=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
"rad"
and"deg"
.
-
class
ColorSpec
(default, help=None, key_type=<bokeh.core.property.enum.Enum object>)[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
DataDistanceSpec
(default=None, help=None)[source]¶ A
DataSpec
property that accepts numeric fixed values for data-space distances, and also provides an associated units property that reports"data"
as the units.Note
Units are always
"data"
.
-
class
DataSpec
(key_type, value_type, default, help=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 sublclasses 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=None, units_default='data', help=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=None, key_type=<bokeh.core.property.enum.Enum object>)[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 = "10pt" # 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=None, key_type=<bokeh.core.property.enum.Enum object>)[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=None, help=None, key_type=<bokeh.core.property.enum.Enum object>, 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
ScreenDistanceSpec
(default=None, help=None)[source]¶ A
DataSpec
property that accepts numeric fixed values for screen distances, and also provides an associated units property that reports"screen"
as the units.Note
Units are always
"screen"
.
-
class
StringSpec
(default, help=None, key_type=<bokeh.core.property.enum.Enum object>)[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_type, units_default, help=None)[source]¶ A
DataSpec
property that accepts numeric fixed values, and also provides an associated units property to store units information.
Helpers¶
-
expr
(expression, transform=None)[source]¶ Convenience function to explicitly return an “expr” specification for a Bokeh
DataSpec
property.Parameters: - expression (Expression) – a computed expression for a
DataSpec
property. - transform (Transform, optional) – a transform to apply (default: None)
Returns: { "expr": expression }
Return type: Note
This function is included for completeness. String values for property specifications are by default interpreted as field names.
- expression (Expression) – a computed expression for a
-
field
(name, transform=None)[source]¶ Convenience function to explicitly return a “field” specification for a Bokeh
DataSpec
property.Parameters: Returns: { "field": name }
Return type: Note
This function is included for completeness. String values for property specifications are by default interpreted as field names.
-
value
(val, transform=None)[source]¶ Convenience function to explicitly return a “value” specification for a Bokeh
DataSpec
property.Parameters: - val (any) – a fixed value to specify for a
DataSpec
property. - transform (Transform, optional) – a transform to apply (default: None)
Returns: { "value": name }
Return type: Note
String values for property specifications are by default interpreted as field names. This function is especially useful when you want to specify a fixed value with text properties.
Example
# The following will take text values to render from a data source # column "text_column", but use a fixed value "12pt" for font size p.text("x", "y", text="text_column", text_font_size=value("12pt"), source=source)
- val (any) – a fixed value to specify for a
Special Properties¶
-
class
Include
(delegate, help='', use_prefix=True)[source]¶ Include “mix-in” property collection in a Bokeh model.
See bokeh.core.property_mixins for more details.
-
class
Override
(**kwargs)[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 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