bokeh.util#

Provide a collection of general utilities useful for implementing Bokeh functionality.

bokeh.util.browser#

Utility functions for helping with operations involving browsers.

class DummyWebBrowser[source]#

A “no-op” web-browser controller.

open(url: str, new: Literal[0, 1, 2] = 0, autoraise: bool = True) bool[source]#

Receive standard arguments and take no action.

get_browser_controller(browser: str | None = None) BrowserLike[source]#

Return a browser controller.

Parameters:

browser (str or None) –

browser name, or None (default: None) If passed the string 'none', a dummy web browser controller is returned.

Otherwise, use the value to select an appropriate controller using the webbrowser standard library module. If the value is None, a system default is used.

Returns:

a web browser controller

Return type:

controller

view(location: str, browser: str | None = None, new: BrowserTarget = 'same', autoraise: bool = True) None[source]#

Open a browser to view the specified location.

Parameters:
  • location (str) – Location to open If location does not begin with “http:” it is assumed to be a file path on the local filesystem.

  • browser (str or None) – what browser to use (default: None) If None, use the system default browser.

  • new (str) –

    How to open the location. Valid values are:

    'same' - open in the current tab

    'tab' - open a new tab in the current window

    'window' - open in a new window

  • autoraise (bool) – Whether to automatically raise the location in a new browser window (default: True)

Returns:

None

bokeh.util.callback_manager#

Provides PropertyCallbackManager and EventCallbackManager mixin classes for adding on_change and on_event callback interfaces to classes.

class EventCallbackManager(*args: Any, **kw: Any)[source]#

A mixin class to provide an interface for registering and triggering event callbacks on the Python side.

on_event(event: str | type[Event], *callbacks: EventCallback) None[source]#

Run callbacks when the specified event occurs on this Model

Not all Events are supported for all Models. See specific Events in bokeh.events for more information on which Models are able to trigger them.

class PropertyCallbackManager(*args: Any, **kw: Any)[source]#

A mixin class to provide an interface for registering and triggering callbacks.

on_change(attr: str, *callbacks: Callable[[str, Any, Any], None]) None[source]#

Add a callback on this object to trigger when attr changes.

Parameters:
  • attr (str) – an attribute name on this object

  • callback (callable) – a callback function to register

Returns:

None

remove_on_change(attr: str, *callbacks: Callable[[str, Any, Any], None]) None[source]#

Remove a callback from this object

trigger(attr: str, old: Any, new: Any, hint: DocumentPatchedEvent | None = None, setter: Setter | None = None) None[source]#

Trigger callbacks for attr on this object.

Parameters:
Returns:

None

bokeh.util.compiler#

Provide functions and classes to help with various JS and CSS compilation.

exception CompilationError(error: dict[str, str] | str)[source]#

A RuntimeError subclass for reporting JS compilation errors.

class AttrDict[source]#

Provide a dict subclass that supports access by named attributes.

class CustomModel(cls: type[HasProps])[source]#

Represent a custom (user-defined) Bokeh model.

class FromFile(path: str)[source]#

A custom model implementation read from a separate source file.

Parameters:

path (str) – The path to the file containing the extension source code

class Implementation[source]#

Base class for representing Bokeh custom model implementations.

class Inline(code: str, file: str | None = None)[source]#

Base class for representing Bokeh custom model implementations that may be given as inline code in some language.

Parameters:
  • code (str) – The source code for the implementation

  • file (str, optional) – A file path to a file containing the source text (default: None)

class JavaScript(code: str, file: str | None = None)[source]#

An implementation for a Bokeh custom model in JavaScript

Example

class MyExt(Model):
    __implementation__ = JavaScript(""" <JavaScript code> """)
class Less(code: str, file: str | None = None)[source]#

An implementation of a Less CSS style sheet.

class TypeScript(code: str, file: str | None = None)[source]#

An implementation for a Bokeh custom model in TypeScript

Example

class MyExt(Model):
    __implementation__ = TypeScript(""" <TypeScript code> """)
bundle_all_models() str | None[source]#

Create a bundle of all models.

bundle_models(models: Sequence[type[HasProps]] | None) str | None[source]#

Create a bundle of selected models.

calc_cache_key(custom_models: dict[str, CustomModel]) str[source]#

Generate a key to cache a custom extension implementation with.

There is no metadata other than the Model classes, so this is the only base to generate a cache key.

We build the model keys from the list of model.full_name. This is not ideal but possibly a better solution can be found found later.

get_cache_hook() Callable[[CustomModel, Implementation], AttrDict | None][source]#

Returns the current cache hook used to look up the compiled code given the CustomModel and Implementation

set_cache_hook(hook: Callable[[CustomModel, Implementation], AttrDict | None]) None[source]#

Sets a compiled model cache hook used to look up the compiled code given the CustomModel and Implementation

bokeh.util.dependencies#

Utilities for checking dependencies

import_optional(mod_name: str) ModuleType | None[source]#

Attempt to import an optional dependency.

Silently returns None if the requested module is not available.

Parameters:

mod_name (str) – name of the optional module to try to import

Returns:

imported module or None, if import fails

import_required(mod_name: str, error_msg: str) module[source]#

Attempt to import a required dependency.

Raises a RuntimeError if the requested module is not available.

Parameters:
  • mod_name (str) – name of the required module to try to import

  • error_msg (str) – error message to raise when the module is missing

Returns:

imported module

Raises:

RuntimeError

bokeh.util.deprecation#

bokeh.util.functions#

Utilities for function introspection.

get_param_info(sig: Signature) tuple[list[str], list[Any]][source]#

Find parameters with defaults and return them.

Parameters:

sig (Signature) – a function signature

Returns:

parameters with defaults

Return type:

tuple(list, list)

bokeh.util.hex#

Functions useful for dealing with hexagonal tilings.

For more information on the concepts employed here, see this informative page

axial_to_cartesian(q: Any, r: Any, size: float, orientation: str, aspect_scale: float = 1) tuple[Any, Any][source]#

Map axial (q,r) coordinates to cartesian (x,y) coordinates of tiles centers.

This function can be useful for positioning other Bokeh glyphs with cartesian coordinates in relation to a hex tiling.

This function was adapted from:

Parameters:
  • q (array[float]) – A NumPy array of q-coordinates for binning

  • r (array[float]) – A NumPy array of r-coordinates for binning

  • size (float) –

    The size of the hexagonal tiling.

    The size is defined as the distance from the center of a hexagon to the top corner for “pointytop” orientation, or from the center to a side corner for “flattop” orientation.

  • orientation (str) – Whether the hex tile orientation should be “pointytop” or “flattop”.

  • aspect_scale (float, optional) –

    Scale the hexagons in the “cross” dimension.

    For “pointytop” orientations, hexagons are scaled in the horizontal direction. For “flattop”, they are scaled in vertical direction.

    When working with a plot with aspect_scale != 1, it may be useful to set this value to match the plot.

Returns:

(array[int], array[int])

cartesian_to_axial(x: Any, y: Any, size: float, orientation: str, aspect_scale: float = 1) tuple[Any, Any][source]#

Map Cartesion (x,y) points to axial (q,r) coordinates of enclosing tiles.

This function was adapted from:

Parameters:
  • x (array[float]) – A NumPy array of x-coordinates to convert

  • y (array[float]) – A NumPy array of y-coordinates to convert

  • size (float) –

    The size of the hexagonal tiling.

    The size is defined as the distance from the center of a hexagon to the top corner for “pointytop” orientation, or from the center to a side corner for “flattop” orientation.

  • orientation (str) – Whether the hex tile orientation should be “pointytop” or “flattop”.

  • aspect_scale (float, optional) –

    Scale the hexagons in the “cross” dimension.

    For “pointytop” orientations, hexagons are scaled in the horizontal direction. For “flattop”, they are scaled in vertical direction.

    When working with a plot with aspect_scale != 1, it may be useful to set this value to match the plot.

Returns:

(array[int], array[int])

hexbin(x: Any, y: Any, size: float, orientation: str = 'pointytop', aspect_scale: float = 1) Any[source]#

Perform an equal-weight binning of data points into hexagonal tiles.

For more sophisticated use cases, e.g. weighted binning or scaling individual tiles proportional to some other quantity, consider using HoloViews.

Parameters:
  • x (array[float]) – A NumPy array of x-coordinates for binning

  • y (array[float]) – A NumPy array of y-coordinates for binning

  • size (float) –

    The size of the hexagonal tiling.

    The size is defined as the distance from the center of a hexagon to the top corner for “pointytop” orientation, or from the center to a side corner for “flattop” orientation.

  • orientation (str, optional) – Whether the hex tile orientation should be “pointytop” or “flattop”. (default: “pointytop”)

  • aspect_scale (float, optional) –

    Match a plot’s aspect ratio scaling.

    When working with a plot with aspect_scale != 1, this parameter can be set to match the plot, in order to draw regular hexagons (instead of “stretched” ones).

    This is roughly equivalent to binning in “screen space”, and it may be better to use axis-aligned rectangular bins when plot aspect scales are not one.

Returns:

DataFrame

The resulting DataFrame will have columns q and r that specify hexagon tile locations in axial coordinates, and a column counts that provides the count for each tile.

Warning

Hex binning only functions on linear scales, i.e. not on log plots.

bokeh.util.logconfig#

Configure the logging system for Bokeh.

By default, logging is not configured, to allow users of Bokeh to have full control over logging policy. However, it is useful to be able to enable logging arbitrarily during when developing Bokeh. This can be accomplished by setting the environment variable BOKEH_PY_LOG_LEVEL. Valid values are, in order of increasing severity:

  • debug

  • info

  • warn

  • error

  • fatal

  • none

The default logging level is none.

basicConfig(**kwargs: Any) None[source]#

A logging.basicConfig() wrapper that also undoes the default Bokeh-specific configuration.

bokeh.util.options#

Utilities for specifying, validating, and documenting configuration options.

class Options(kw: dict[str, Any])[source]#

Leverage the Bokeh properties type system for specifying and validating configuration options.

Subclasses of Options specify a set of configuration options using standard Bokeh properties:

class ConnectOpts(Options):

    host = String(default="127.0.0.1", help="a host value")

    port = Int(default=5590, help="a port value")

Then a ConnectOpts can be created by passing a dictionary containing keys and values corresponding to the configuration options, as well as any additional keys and values. The items corresponding to the properties on ConnectOpts will be *removed* from the dictionary. This can be useful for functions that accept their own set of config keyword arguments in addition to some set of Bokeh model properties.

bokeh.util.paths#

bokehjsdir(dev: bool = False) str[source]#

Get the location of the bokehjs source files. If dev is True, the files in bokehjs/build are preferred. Otherwise uses the files in bokeh/server/static.

serverdir() str[source]#

Get the location of the server subpackage

bokeh.util.serialization#

Functions for helping with serialization and deserialization of Bokeh objects.

Certain NumPy array dtypes can be serialized to a binary format for performance and efficiency. The list of supported dtypes is:

  • np.int8

  • np.uint32

  • np.uint16

  • np.float64

  • np.int16

  • np.uint8

  • np.int32

  • np.float32

  • np.bool

array_encoding_disabled(array: npt.NDArray[Any]) bool[source]#

Determine whether an array may be binary encoded.

The NumPy array dtypes that can be encoded are:

  • np.int8

  • np.uint32

  • np.uint16

  • np.float64

  • np.int16

  • np.uint8

  • np.int32

  • np.float32

  • np.bool

Parameters:

array (np.ndarray) – the array to check

Returns:

bool

convert_date_to_datetime(obj: date) float[source]#

Convert a date object to a datetime

Parameters:

obj (date) – the object to convert

Returns:

datetime

convert_datetime_array(array: npt.NDArray[Any]) npt.NDArray[np.floating[Any]][source]#

Convert NumPy datetime arrays to arrays to milliseconds since epoch.

Parameters:

array

(obj) A NumPy array of datetime to convert

If the value passed in is not a NumPy array, it will be returned as-is.

Returns:

array

convert_datetime_type(obj: Any | pd.Timestamp | pd.Timedelta | dt.datetime | dt.date | dt.time | np.datetime64) float[source]#

Convert any recognized date, time, or datetime value to floating point milliseconds since epoch.

Arg:

obj (object) : the object to convert

Returns:

milliseconds

Return type:

float

convert_timedelta_type(obj: dt.timedelta | np.timedelta64) float[source]#

Convert any recognized timedelta value to floating point absolute milliseconds.

Arg:

obj (object) : the object to convert

Returns:

milliseconds

Return type:

float

is_datetime_type(obj: Any) TypeGuard[dt.time | dt.datetime | np.datetime64][source]#

Whether an object is any date, time, or datetime type recognized by Bokeh.

Arg:

obj (object) : the object to test

Returns:

True if obj is a datetime type

Return type:

bool

is_timedelta_type(obj: Any) TypeGuard[dt.timedelta | np.timedelta64][source]#

Whether an object is any timedelta type recognized by Bokeh.

Arg:

obj (object) : the object to test

Returns:

True if obj is a timedelta type

Return type:

bool

make_globally_unique_id() ID[source]#

Return a globally unique UUID.

Some situations, e.g. id’ing dynamically created Divs in HTML documents, always require globally unique IDs.

Returns:

str

make_id() ID[source]#

Return a new unique ID for a Bokeh object.

Normally this function will return simple monotonically increasing integer IDs (as strings) for identifying Bokeh objects within a Document. However, if it is desirable to have globally unique for every object, this behavior can be overridden by setting the environment variable BOKEH_SIMPLE_IDS=no.

Returns:

str

transform_array(array: npt.NDArray[Any]) npt.NDArray[Any][source]#

Transform a ndarray into a serializable ndarray.

Converts un-serializable dtypes and returns JSON serializable format

Parameters:

array (np.ndarray) – a NumPy array to be transformed

Returns:

ndarray

transform_series(series: pd.Series[Any] | pd.Index) npt.NDArray[Any][source]#

Transforms a Pandas series into serialized form

Parameters:

series (pd.Series) – the Pandas series to transform

Returns:

ndarray

bokeh.util.token#

Utilities for generating and manipulating session IDs.

A session ID would typically be associated with each browser tab viewing an application or plot. Each session has its own state separate from any other sessions hosted by the server.

check_session_id_signature(session_id: str, secret_key: bytes | None = None, signed: bool | None = False) bool[source]#

Check the signature of a session ID, returning True if it’s valid.

The server uses this function to check whether a session ID was generated with the correct secret key. If signed sessions are disabled, this function always returns True.

check_token_signature(token: str, secret_key: bytes | None = None, signed: bool = False) bool[source]#

Check the signature of a token and the contained signature.

The server uses this function to check whether a token and the contained session id was generated with the correct secret key. If signed sessions are disabled, this function always returns True.

Parameters:
  • token (str) – The token to check

  • secret_key (str, optional) – Secret key (default: value of BOKEH_SECRET_KEY environment variable)

  • signed (bool, optional) – Whether to check anything (default: value of BOKEH_SIGN_SESSIONS environment variable)

Returns:

bool

generate_jwt_token(session_id: ID, secret_key: bytes | None = None, signed: bool = False, extra_payload: TokenPayload | None = None, expiration: int = 300) str[source]#

Generates a JWT token given a session_id and additional payload.

Parameters:
  • session_id (str) – The session id to add to the token

  • secret_key (str, optional) – Secret key (default: value of BOKEH_SECRET_KEY environment variable)

  • signed (bool, optional) – Whether to sign the session ID (default: value of BOKEH_SIGN_SESSIONS environment variable)

  • extra_payload (dict, optional) – Extra key/value pairs to include in the Bokeh session token

  • expiration (int, optional) – Expiration time

Returns:

str

generate_secret_key() str[source]#

Generate a new securely-generated secret key appropriate for SHA-256 HMAC signatures.

This key could be used to sign Bokeh server session IDs, for example.

generate_session_id(secret_key: bytes | None = None, signed: bool = False) ID[source]#

Generate a random session ID.

Typically, each browser tab connected to a Bokeh application has its own session ID. In production deployments of a Bokeh app, session IDs should be random and unguessable - otherwise users of the app could interfere with one another.

get_session_id(token: str) ID[source]#

Extracts the session id from a JWT token.

Parameters:

token (str) – A JWT token containing the session_id and other data.

Returns:

str

get_token_payload(token: str) Dict[str, Any][source]#

Extract the payload from the token.

Parameters:

token (str) – A JWT token containing the session_id and other data.

Returns:

dict

bokeh.util.strings#

Functions useful for string manipulations or encoding.

append_docstring(docstring: str | None, extra: str) str | None[source]#

Safely append to docstrings.

When Python is executed with the -OO option, doc strings are removed and replaced the value None. This function guards against appending the extra content in that case.

Parameters:
  • docstring (str or None) – The docstring to format, or None

  • extra (str) – the content to append if docstring is not None

Returns:

str or None

format_docstring(docstring: None, *args: Any, **kwargs: Any) None[source]#
format_docstring(docstring: str, *args: Any, **kwargs: Any) str

Safely format docstrings.

When Python is executed with the -OO option, doc strings are removed and replaced the value None. This function guards against applying the string formatting options in that case.

Parameters:
  • docstring (str or None) – The docstring to format, or None

  • args (tuple) – string formatting arguments for the docsring

  • kwargs (dict) – string formatting arguments for the docsring

Returns:

str or None

indent(text: str, n: int = 2, ch: str = ' ') str[source]#

Indent all the lines in a given block of text by a specified amount.

Parameters:
  • text (str) – The text to indent

  • n (int, optional) – The amount to indent each line by (default: 2)

  • ch (char, optional) – What character to fill the indentation with (default: “ “)

nice_join(seq: Iterable[str], sep: str = ', ', conjuction: str = 'or') str[source]#

Join together sequences of strings into English-friendly phrases using the conjunction or when appropriate.

Parameters:
  • seq (seq[str]) – a sequence of strings to nicely join

  • sep (str, optional) – a sequence delimiter to use (default: “, “)

  • conjunction (str or None, optional) – a conjuction to use for the last two items, or None to reproduce basic join behaviour (default: “or”)

Returns:

a joined string

Examples

>>> nice_join(["a", "b", "c"])
'a, b or c'
snakify(name: str, sep: str = '_') str[source]#

Convert CamelCase to snake_case.

bokeh.util.tornado#

Internal utils related to Tornado

bokeh.util.terminal#

Provide utilities for formatting terminal output.

bokeh.util.version#

Provide a version for the Bokeh library.

This module uses versioneer to manage version strings. During development, versioneer will compute a version string from the current git revision. For packaged releases based off tags, the version string is hard coded in the files packaged for distribution.

__version__#

The full version string for this installed Bokeh library

Functions:
base_version:

Return the base version string, without any “dev”, “rc” or local build information appended.

is_full_release:

Return whether the current installed version is a full release.

bokeh.util.warnings#

Provide Bokeh-specific warning subclasses.

The primary use of these subclasses to to force them to be unconditionally displayed to users by default.

exception BokehDeprecationWarning[source]#

A Bokeh-specific DeprecationWarning subclass.

Used to selectively filter Bokeh deprecations for unconditional display.

exception BokehUserWarning[source]#

A Bokeh-specific UserWarning subclass.

Used to selectively filter Bokeh warnings for unconditional display.

find_stack_level() int[source]#

Find the first place in the stack that is not inside Bokeh.

Inspired by: pandas.util._exceptions.find_stack_level