Properties System

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 classes provide for easy bulk addition of properties to model classes.

bokeh.properties

Below is the full class inheritance diagram for all standard Bokeh property types. Click on any node to be taken to the corresponding documention.

Inheritance diagram of bokeh.properties

Properties are objects that can be assigned as class level attributes on Bokeh models, to provide automatic serialization and validation.

For example, the following defines a model that has integer, string, and list[float] properties:

class Model(HasProps):
    foo = Int
    bar = String
    baz = List(Float)

The properties of this class can be initialized by specifying keyword arguments to the initializer:

m = Model(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):
  File "<stdin>", line 1, in <module>
  File "/Users/bryan/work/bokeh/bokeh/properties.py", line 585, in __setattr__
    super(HasProps, self).__setattr__(name, value)
  File "/Users/bryan/work/bokeh/bokeh/properties.py", line 159, in __set__
    raise e
  File "/Users/bryan/work/bokeh/bokeh/properties.py", line 152, in __set__
    self.validate(value)
  File "/Users/bryan/work/bokeh/bokeh/properties.py", line 707, in validate
    (nice_join([ cls.__name__ for cls in self._underlying_type ]), value, type(value).__name__))
ValueError: expected a value of type int8, int16, int32, int64 or int, got 2.3 of type float

Additionally, properties know how to serialize themselves, to be understood by BokehJS.

class Angle(default=None, help=None)

Angle type property.

class Any(default=None, help=None)

Any type property accepts any values.

class Array(item_type, default=None, help=None)

NumPy array type property.

class Bool(default=None, help=None)

Boolean type property.

class Byte(default=0, help=None)

Byte type property.

class Color(default=None, help=None)

Accepts color definition in a variety of ways, and produces an appropriate serialization of its value for whatever backend.

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.)

class ColorSpec(field_or_value=None, field=None, value=None, default=<class 'bokeh.properties._NotSet'>, help=None)

Subclass of DataSpec for specifying colors.

Although this serves the same role as a DataSpec, its usage is somewhat different because:

  • Specifying a fixed value is much more common
  • Strings can be both field identifiers or refer to one of the SVG Named Colors (or be a hex value starting with “#”)
  • There are no units

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. Otherwise, it is treated as a field name.

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.)

Unlike DataSpec, ColorSpecs do not have a “units” property.

When reading out a ColorSpec, it returns a tuple, hex value, or field name

There are two common use cases for ColorSpec: setting a constant value, and indicating a field name to look for on the datasource:

>>> class Bar(HasProps):
...     col = ColorSpec(default="green")
...     col2 = ColorSpec("colorfield")
>>> b = Bar()
>>> b.col = "red"  # sets a fixed value of red
>>> b.col
"red"
>>> b.col = "myfield"  # Use the datasource field named "myfield"
>>> b.col
"myfield"

For more examples, see tests/test_glyphs.py

classmethod isconst(arg)

Returns True if the argument is a literal color. Check for a well-formed hexadecimal color value.

class Complex(default=None, help=None)

Complex floating point type property.

class ContainerProperty(default=None, help=None)

Base class for Container-like type properties.

class DashPattern(default=[], help=None)

Dash type property.

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 DataSpec(field=None, units='data', min_value=None, default=<class 'bokeh.properties._NotSet'>, help=None)

Because the BokehJS glyphs support a fixed value or a named field for most data fields, we capture that in this descriptor. Fields can have a fixed value, or be a name that is looked up on the datasource (usually as a column or record array field). Numerical data can also have units of screen or data space.

We mirror the JS convention in this Python descriptor. For details, see renderers/properties.coffee in BokehJS, and specifically the select() function.

There are multiple ways to set a DataSpec, illustrated below with comments and example code.

Setting DataSpecs

Simple example:

class Foo(HasProps):
    x = DataSpec("x", units="data")

f = Foo()
f.x = "fieldname"  # Use the datasource field named "fieldname"
f.x = 12           # A fixed value of 12

Can provide a dict with the fields explicitly named:

f.width = {"name": "foo"}
f.size = {"name": "foo", "units": "screen"}

Reading DataSpecs

In the cases when the dataspec is set to just a field name or a fixed value, then those are returned. If the no values have been set, then the value of to_dict() is returned.

In all cases, to determine the full dict that will be used to represent this dataspec, use the to_dict() method.

Implementation

The DataSpec instance is stored in the class dict, and acts as a descriptor. Thus, it is shared between all instances of the class. Instance-specific data is stored in the instance dict, in a private variable named _[attrname]. This stores the actual value that the user last set (and does not exist if the user has not yet set the value).

class Date(default=datetime.date(2015, 3, 25), help=None)

Date (not datetime) type property.

class Datetime(default=datetime.date(2015, 3, 25), help=None)

Datetime type property.

class Dict(keys_type, values_type, default={}, help=None)

Python dict type property.

If a default value is passed in, then a shallow copy of it will be used for each new use of this property.

class Either(tp1, tp2, *type_params, **kwargs)

Takes a list of valid properties and validates against them in succession.

class Enum(enum, *values, **kwargs)

An Enum with a list of allowed values. The first value in the list is the default value, unless a default is provided with the “default” keyword argument.

class Event(default=None, help=None)

Event type property.

class Float(default=None, help=None)

Floating point type property.

class Function(default=None, help=None)

Function type property.

class Include(delegate, help='', use_prefix=True)

Include other properties from mixin Models, with a given prefix.

class Instance(instance_type, default=None, help=None)

Instance type property, for references to other Models in the object graph.

class Int(default=None, help=None)

Signed integer type property.

class Interval(interval_type, start, end, default=None, help=None)

Range type property ensures values are contained inside a given interval.

class List(item_type, default=[], help=None)

Python list type property.

class ParameterizedProperty(default=None, help=None)

Base class for Properties that have type parameters, e.g. List(String).

class Percent(default=None, help=None)

Percentage type property.

Percents are useful for specifying alphas and coverage and extents; more semantically meaningful than Float(0..1).

class PrimitiveProperty(default=None, help=None)

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.

class Property(default=None, help=None)

Base class for all type properties.

classmethod autocreate(name=None)

Called by the metaclass to create a new instance of this descriptor if the user just assigned it to a property without trailing parentheses.

class Regex(regex, default=None, help=None)

Regex type property validates that text values match the given regular expression.

class RelativeDelta(default={}, help=None)

RelativeDelta type property for time deltas.

class Seq(item_type, default=None, help=None)

Sequence (list, tuple) type property.

class Size(default=None, help=None)

Size type property.

Note

Size is equivalent to an unsigned int.

class String(default=None, help=None)

String type property.

class This(default=None, help=None)

A reference to an instance of the class being defined.

class Tuple(tp1, tp2, *type_params, **kwargs)

Tuple type property.

bokeh.mixins

class FillProps(**properties)

Properties to use when performing fill operations while rendering.

Mirrors the BokehJS properties.Fill class.

fill_alpha

property type: DataSpec

An alpha value to use to fill paths with.

Acceptable values are floating point numbers between 0 (transparent) and 1 (opaque).

fill_color

property type: ColorSpec

A color to use to fill paths with.

Acceptable values are:

  • any of the 147 named CSS colors, e.g 'green', 'indigo'
  • an RGB(A) hex value, e.g., '#FF0000', '#44444444'
  • a 3-tuple of integers (r,g,b) between 0 and 255
  • a 4-tuple of (r,g,b,a) where r,g,b are integers between 0..255 and a is between 0..1
class LineProps(**properties)

Properties to use when performing stroke operations while rendering.

Mirrors the BokehJS properties.Line class.

line_alpha

property type: DataSpec

An alpha value to use to stroke paths with.

Acceptable values are floating point numbers between 0 (transparent) and 1 (opaque).

line_cap

property type: Enum(‘butt’, ‘round’, ‘square’)

How path segments should be terminated.

Acceptable values are:

  • 'butt' butt_cap
  • 'round' round_cap
  • 'square' square_cap
line_color

property type: ColorSpec

A color to use to stroke paths with.

Acceptable values are:

  • any of the 147 named CSS colors, e.g 'green', 'indigo'
  • an RGB(A) hex value, e.g., '#FF0000', '#44444444'
  • a 3-tuple of integers (r,g,b) between 0 and 255
  • a 4-tuple of (r,g,b,a) where r,g,b are integers between 0..255 and a is between 0..1
line_dash

property type: DashPattern

How should the line be dashed.

line_dash_offset

property type: Int

The distance into the line_dash (in pixels) that the pattern should start from.

line_join

property type: Enum(‘miter’, ‘round’, ‘bevel’)

How path segments should be joined together.

Acceptable values are:

  • 'miter' miter_join
  • 'round' round_join
  • 'bevel' bevel_join
line_width

property type: DataSpec

Stroke width in units of pixels.

class TextProps(**properties)

Properties to use when performing text drawing operations while rendering.

Mirrors the BokehJS properties.Text class.

Note

There is currently only support for filling text. An interface to stroke the outlines of text has not yet been exposed.

text_align

property type: Enum(‘left’, ‘right’, ‘center’)

Horizontal anchor point to use when rendering text.

Acceptable values are:

  • 'left'
  • 'right'
  • 'center'
text_alpha

property type: DataSpec

An alpha value to use to fill text with.

Acceptable values are floating point numbers between 0 (transparent) and 1 (opaque).

text_baseline

property type: Enum(‘top’, ‘middle’, ‘bottom’, ‘alphabetic’, ‘hanging’)

Vertical anchor point to use when rendering text.

Acceptable values are:

  • 'top'
  • 'middle'
  • 'bottom'
  • 'alphabetic'
  • 'hanging'
text_color

property type: ColorSpec

A color to use to fill text with.

Acceptable values are:

  • any of the 147 named CSS colors, e.g 'green', 'indigo'
  • an RGB(A) hex value, e.g., '#FF0000', '#44444444'
  • a 3-tuple of integers (r,g,b) between 0 and 255
  • a 4-tuple of (r,g,b,a) where r,g,b are integers between 0..255 and a is between 0..1
text_font

property type: String

Name of a font to use for rendering text, e.g., 'times', 'helvetica'.

text_font_style

property type: Enum(‘normal’, ‘italic’, ‘bold’)

A style to use for rendering text.

Acceptable values are:

  • 'normal' normal text
  • 'italic' italic text
  • 'bold' bold text