Anaconda Enterprise: Documentation

# 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 `bokeh.util.browser.``DummyWebBrowser`

  A “no-op” web-browser controller.

  `open`(url, new=0, autoraise=True)

    Receive standard arguments and take no action.

`bokeh.util.browser.``get_browser_controller`(browser=None)

  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. In the value is `None` then a system default is used.

  Note

  If the environment variable `BOKEH_BROWSER` is set, it will take precedence.

  Returns: | a web browser controller
  Return type: | controller

`bokeh.util.browser.``view`(location, browser=None, new='same', autoraise=True)

  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 `bokeh.util.callback_manager.``EventCallbackManager`(*args, **kw)

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

class `bokeh.util.callback_manager.``PropertyCallbackManager`(*args, **kw)

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

  `on_change`(attr, *callbacks)

    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, *callbacks)

    Remove a callback from this object

  `trigger`(attr, old, new, hint=None, setter=None)

    Trigger callbacks for `attr` on this object.

    Parameters:

    - attr (str) –
    - old (object) –
    - new (object) –

    Returns: | None

## `bokeh.util.compiler`

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

exception `bokeh.util.compiler.``CompilationError`(error)

  A RuntimeError subclass for reporting JS compilation errors.

class `bokeh.util.compiler.``AttrDict`

  Provide a dict subclass that supports access by named attributes.

`bokeh.util.compiler.``bundle_models`(models)

  Create a bundle of models.

`bokeh.util.compiler.``exts` = ('.coffee', '.ts', '.tsx', '.js', '.css', '.less')

  recognized extensions that can be compiled

## `bokeh.util.dependencies`

Utilities for checking dependencies

`bokeh.util.dependencies.``detect_phantomjs`()

  Detect if PhantomJS is avaiable in PATH.

`bokeh.util.dependencies.``import_optional`(mod_name)

  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

`bokeh.util.dependencies.``import_required`(mod_name, error_msg)

  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.future`

Utilities for Py2/Py3 interop.

`bokeh.util.future.``with_metaclass`(meta, *bases)

  Add metaclasses in both Python 2 and Python 3.

  Function from jinja2/_compat.py. License: BSD.

  Use it like this:

      class BaseForm(object):
          pass

      class FormType(type):
          pass

      class Form(with_metaclass(FormType, BaseForm)):
          pass

  This requires a bit of explanation: the basic idea is to make a dummy metaclass for one level of class instantiation that replaces itself with the actual metaclass. Because of internal type checks we also need to make sure that we downgrade the custom metaclass for one level to something closer to type (that’s why __call__ and __init__ comes back from type etc.).

  This has the advantage over six.with_metaclass of not introducing dummy classes into the final MRO.

## `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`.

`bokeh.util.logconfig.``basicConfig`(*args, **kwargs)

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

## `bokeh.util.notebook`

Functions useful for loading Bokeh code and data in Jupyter/Zeppelin notebooks.

`bokeh.util.notebook.``get_comms`(target_name)

  Create a Jupyter comms object for a specific target, that can be used to update Bokeh documents in the Jupyter notebook.

  Parameters: | target_name (str) – the target name the Comms object should connect to

  Returns
    Jupyter Comms

`bokeh.util.notebook.``load_notebook`(resources=None, verbose=False, hide_banner=False, load_timeout=5000, notebook_type='jupyter')

  Prepare the IPython notebook for displaying Bokeh plots.

  Parameters:

  - resources (Resource, optional) – how and where to load BokehJS from (default: CDN)
  - verbose (bool, optional) – whether to report detailed settings (default: False)
  - hide_banner (bool, optional) – whether to hide the Bokeh banner (default: False)
  - load_timeout (int, optional) – Timeout in milliseconds when plots assume load timed out (default: 5000)
  - notebook_type (string) – notebook_type (default: jupyter)

  Warning

  Clearing the output cell containing the published BokehJS resources HTML code may cause Bokeh CSS styling to be removed.

  Returns: | None

## `bokeh.util.options`

Utilities for specifying, validating, and documenting configuration options.

class `bokeh.util.options.``Options`(kw=None)

  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`

`bokeh.util.paths.``bokehjsdir`(dev=False)

  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.

`bokeh.util.paths.``serverdir`()

  Get the location of the server subpackage

## `bokeh.util.platform`

Functions for testing what kind of Python or Python environment is in use.

`bokeh.util.platform.``is_py3`()

  Test whether we are running Python 3.

  Returns
    True if we are running Python 3, otherwise False

`bokeh.util.platform.``is_pypy`()

  Test whether we are running PyPy.

  Returns
    True if we are inside PyPy, otherwise False

## `bokeh.util.plot_utils`

## `bokeh.util.serialization`

Functions for helping with serialization and deserialization of Bokeh objects.

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

- `np.int8`
- `np.float64`
- `np.uint16`
- `np.uint8`
- `np.int32`
- `np.int16`
- `np.uint32`
- `np.float32`

`bokeh.util.serialization.``array_encoding_disabled`(array)

  Determine whether an array may be binary encoded.

  The NumPy array dtypes that can be encoded are:

  - `np.int8`
  - `np.float64`
  - `np.uint16`
  - `np.uint8`
  - `np.int32`
  - `np.int16`
  - `np.uint32`
  - `np.float32`

  Parameters: | array (np.ndarray) – the array to check
  Returns: | bool

`bokeh.util.serialization.``convert_datetime_type`(obj)

  Convert any recognized date, datetime or time delta value to floating point milliseconds

  Date and Datetime values are converted to milliseconds since epoch.

  TimeDeleta values are converted to absolute milliseconds.

  Arg:
    obj (object) : the object to convert

  Returns: | milliseconds
  Return type: | float

`bokeh.util.serialization.``decode_base64_dict`(data)

  Decode a base64 encoded array into a NumPy array.

  Parameters: | data (dict) – encoded array data to decode

  Data should have the format encoded by `encode_base64_dict()`.

  Returns: | np.ndarray

`bokeh.util.serialization.``encode_base64_dict`(array)

  Encode a NumPy array using base64:

  The encoded format is a dict with the following structure:

      {
          '__ndarray__' : << base64 encoded array data >>,
          'shape'       : << array shape >>,
          'dtype'       : << dtype name >>,
      }

  Parameters: | array (np.ndarray) – an array to encode
  Returns: | dict

`bokeh.util.serialization.``encode_binary_dict`(array, buffers)

  Send a numpy array as an unencoded binary buffer

  The encoded format is a dict with the following structure:

      {
          '__buffer__' :  << an ID to locate the buffer >>,
          'shape'      : << array shape >>,
          'dtype'      : << dtype name >>,
          'order'      : << byte order at origin (little or big)>>
      }

  Parameters:

  - array (np.ndarray) – an array to encode
  - buffers (set) –

    Set to add buffers to

    This is an “out” parameter. The values it contains will be modified in-place.

  Returns: | dict

`bokeh.util.serialization.``is_datetime_type`(obj)

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

  Arg:
    obj (object) : the object to test

  Returns: | True if `obj` is a datetime type
  Return type: | bool

`bokeh.util.serialization.``make_id`()

  Return a new unique ID for a Bokeh object.

  Normally this function will return UUIDs to use for identifying Bokeh objects. This is especally important for Bokeh objects stored on a Bokeh server. However, it is convenient to have more human-readable IDs during development, so this behavior can be overridden by setting the environment variable `BOKEH_SIMPLE_IDS=yes`.

`bokeh.util.serialization.``serialize_array`(array, force_list=False, buffers=None)

  Transforms a NumPy array into serialized form.

  Parameters:

  - array (np.ndarray) – the NumPy array to transform
  - force_list (bool, optional) – whether to only output to standard lists This function can encode some dtypes using a binary encoding, but setting this argument to True will override that and cause only standard Python lists to be emitted. (default: False)
  - buffers (set, optional) –

    If binary buffers are desired, the buffers parameter may be provided, and any columns that may be sent as binary buffers will be added to the set. If None, then only base64 encodinfg will be used (default: None)

    If force_list is True, then this value will be ignored, and no buffers will be generated.

    This is an “out” parameter. The values it contains will be modified in-place.

  Returns: | list or dict

`bokeh.util.serialization.``transform_array`(array, force_list=False, buffers=None)

  Transform a NumPy arrays into serialized format

  Converts un-serializable dtypes and returns JSON serializable format

  Parameters:

  - array (np.ndarray) – a NumPy array to be transformed
  - force_list (bool, optional) – whether to only output to standard lists This function can encode some dtypes using a binary encoding, but setting this argument to True will override that and cause only standard Python lists to be emitted. (default: False)
  - buffers (set, optional) –

    If binary buffers are desired, the buffers parameter may be provided, and any columns that may be sent as binary buffers will be added to the set. If None, then only base64 encodinfg will be used (default: None)

    If force_list is True, then this value will be ignored, and no buffers will be generated.

    This is an “out” parameter. The values it contains will be modified in-place.

  Returns: | JSON

`bokeh.util.serialization.``transform_array_to_list`(array)

  Transforms a NumPy array into a list of values

  Parameters: | array (np.nadarray) – the NumPy array series to transform
  Returns: | list or dict

`bokeh.util.serialization.``transform_column_source_data`(data, buffers=None, cols=None)

  Transform ColumnSourceData data to a serialized format

  Parameters:

  - data (dict) – the mapping of names to data columns to transform
  - buffers (set, optional) –

    If binary buffers are desired, the buffers parameter may be provided, and any columns that may be sent as binary buffers will be added to the set. If None, then only base64 encodinfg will be used (default: None)

    This is an “out” parameter. The values it contains will be modified in-place.

  - cols (list[str], optional) – Optional list of subset of columns to transform. If None, all columns will be transformed (default: None)

  Returns: | JSON compatible dict

`bokeh.util.serialization.``transform_series`(series, force_list=False, buffers=None)

  Transforms a Pandas series into serialized form

  Parameters:

  - series (pd.Series) – the Pandas series to transform
  - force_list (bool, optional) – whether to only output to standard lists This function can encode some dtypes using a binary encoding, but setting this argument to True will override that and cause only standard Python lists to be emitted. (default: False)
  - buffers (set, optional) –

    If binary buffers are desired, the buffers parameter may be provided, and any columns that may be sent as binary buffers will be added to the set. If None, then only base64 encodinfg will be used (default: None)

    If force_list is True, then this value will be ignored, and no buffers will be generated.

    This is an “out” parameter. The values it contains will be modified in-place.

  Returns: | list or dict

`bokeh.util.serialization.``traverse_data`(obj, use_numpy=True, buffers=None)

  Recursively traverse an object until a flat list is found.

  If NumPy is available, the flat list is converted to a numpy array and passed to transform_array() to handle `nan`, `inf`, and `-inf`.

  Otherwise, iterate through all items, converting non-JSON items

  Parameters:

  - obj (list) – a list of values or lists
  - use_numpy (bool, optional) – This argument is only useful for testing (default: True)

## `bokeh.util.session_id`

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.

`bokeh.util.session_id.``check_session_id_signature`(session_id, secret_key=None, signed=False)

  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.

  Parameters:

  - session_id (str) – The session ID to check
  - secret_key (str, optional) – Secret key (default: value of ‘BOKEH_SECRET_KEY’ env var)
  - signed (bool, optional) – Whether to check anything (default: value of ‘BOKEH_SIGN_SESSIONS’ env var)

`bokeh.util.session_id.``generate_secret_key`()

  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.

`bokeh.util.session_id.``generate_session_id`(secret_key=None, signed=False)

  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.

  If session IDs are signed with a secret key, the server can verify that the generator of the session ID was “authorized” (the generator had to know the secret key). This can be used to have a separate process, such as another web application, which generates new sessions on a Bokeh server. This other process may require users to log in before redirecting them to the Bokeh server with a valid session ID, for example.

  Parameters:

  - secret_key (str, optional) – Secret key (default: value of ‘BOKEH_SECRET_KEY’ env var)
  - signed (bool, optional) – Whether to sign the session ID (default: value of ‘BOKEH_SIGN_SESSIONS’ env var)

## `bokeh.util.string`

Functions useful for string manipulations or encoding.

`bokeh.util.string.``decode_utf8`(u)

  Decode a sequence of bytes to a UTF-8 string

  Parameters: | u (str) – the bytes to decode
  Returns: | UTF-8 string

`bokeh.util.string.``encode_utf8`(u)

  Encode a UTF-8 string to a sequence of bytes.

  Parameters: | u (str) – the string to encode
  Returns: | bytes

`bokeh.util.string.``format_docstring`(docstring, *args, **kwargs)

  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

`bokeh.util.string.``nice_join`(seq, sep=', ')

  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: ”, ”)

  Returns: | a joined string

  Examples

      >>> nice_join(["a", "b", "c"])
      'a, b or c'

`bokeh.util.string.``snakify`(name, sep='_')

  Convert CamelCase to snake_case.

## `bokeh.util.testing`

Functions to help with testing Bokeh and reporting issues.

`bokeh.util.testing.``skipIfPy3`(message)

  unittest decorator to skip a test for Python 3

`bokeh.util.testing.``skipIfPyPy`(message)

  unittest decorator to skip a test for PyPy

## `bokeh.util.tornado`

Internal utils related to Tornado

`bokeh.util.tornado.``yield_for_all_futures`(*args, **kwargs)

  Converts result into a Future by collapsing any futures inside result.

  If result is a Future we yield until it’s done, then if the value inside the Future is another Future we yield until it’s done as well, and so on.

## `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.

`bokeh.util.version.``__version__`

  The full version string for this installed Bokeh library

`bokeh.util.version.``__base_version__`

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

## `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 `bokeh.util.warnings.``BokehDeprecationWarning`

  A Bokeh-specific `DeprecationWarning` subclass.

  Used to selectively filter Bokeh deprecations for unconditional display.

exception `bokeh.util.warnings.``BokehUserWarning`

  A Bokeh-specific `UserWarning` subclass.

  Used to selectively filter Bokeh warnings for unconditional display.