reactive Module#

reactive Module#

Declares Syncable and Reactive classes which provides baseclasses for Panel components which sync their state with one or more bokeh models rendered on the frontend.

class panel.reactive.Reactive(refs=None, **params)[source]#

Bases: Syncable, Viewable

Reactive is a Viewable object that also supports syncing between the objects parameters and the underlying bokeh model either via the defined pyviz_comms.Comm type or using bokeh server.

In addition it defines various methods which make it easy to link the parameters to other objects.

Parameters inherited from:

panel.viewable.Layoutable: align, aspect_ratio, css_classes, design, height, min_width, min_height, max_width, max_height, margin, styles, stylesheets, tags, width, width_policy, height_policy, sizing_mode, visible

panel.viewable.Viewable: loading

clone(**params) β†’ Viewable[source]#

Makes a copy of the object sharing the same parameters.

Parameters:

params (Keyword arguments override the parameters on the clone.) –

Return type:

Cloned Viewable object

controls(parameters: List[str] = [], jslink: bool = True, **kwargs) β†’ Panel[source]#

Creates a set of widgets which allow manipulating the parameters on this instance. By default all parameters which support linking are exposed, but an explicit list of parameters can be provided.

Parameters:
  • parameters (list(str)) – An explicit list of parameters to return controls for.

  • jslink (bool) – Whether to use jslinks instead of Python based links. This does not allow using all types of parameters.

  • kwargs (dict) – Additional kwargs to pass to the Param pane(s) used to generate the controls widgets.

Return type:

A layout of the controls

embed(max_states: int = 1000, max_opts: int = 3, json: bool = False, json_prefix: str = '', save_path: str = './', load_path: Optional[str] = None, progress: bool = False, states={}) β†’ None[source]#

Renders a static version of a panel in a notebook by evaluating the set of states defined by the widgets in the model. Note this will only work well for simple apps with a relatively small state space.

Parameters:
  • max_states (int) – The maximum number of states to embed

  • max_opts (int) – The maximum number of states for a single widget

  • json (boolean (default=True)) – Whether to export the data to json files

  • json_prefix (str (default='')) – Prefix for JSON filename

  • save_path (str (default='./')) – The path to save json files to

  • load_path (str (default=None)) – The path or URL the json files will be loaded from.

  • progress (boolean (default=False)) – Whether to report progress

  • states (dict (default={})) – A dictionary specifying the widget values to embed for each widget

get_root(doc: Optional[Document] = None, comm: Optional[Comm] = None, preprocess: bool = True) β†’ Model[source]#

Returns the root model and applies pre-processing hooks

Parameters:
  • doc (bokeh.Document) – Bokeh document the bokeh model will be attached to.

  • comm (pyviz_comms.Comm) – Optional pyviz_comms when working in notebook

  • preprocess (boolean (default=True)) – Whether to run preprocessing hooks

Return type:

Returns the bokeh model corresponding to this panel object

jscallback(args: Dict[str, Any] = {}, **callbacks: str) β†’ Callback[source]#

Allows defining a JS callback to be triggered when a property changes on the source object. The keyword arguments define the properties that trigger a callback and the JS code that gets executed.

Parameters:
  • args (dict) – A mapping of objects to make available to the JS callback

  • **callbacks (dict) – A mapping between properties on the source model and the code to execute when that property changes

Returns:

callback – The Callback which can be used to disable the callback.

Return type:

Callback

Links properties on the this Reactive object to those on the target Reactive object in JS code.

Supports two modes, either specify a mapping between the source and target model properties as keywords or provide a dictionary of JS code snippets which maps from the source parameter to a JS code snippet which is executed when the property changes.

Parameters:
  • target (panel.viewable.Viewable | bokeh.model.Model | holoviews.core.dimension.Dimensioned) – The target to link the value to.

  • code (dict) – Custom code which will be executed when the widget value changes.

  • args (dict) – A mapping of objects to make available to the JS callback

  • bidirectional (boolean) – Whether to link source and target bi-directionally

  • **links (dict) – A mapping between properties on the source model and the target model property to link it to.

Returns:

link – The GenericLink which can be used unlink the widget and the target model.

Return type:

GenericLink

Links the parameters on this Reactive object to attributes on the target Parameterized object.

Supports two modes, either specify a mapping between the source and target object parameters as keywords or provide a dictionary of callbacks which maps from the source parameter to a callback which is triggered when the parameter changes.

Parameters:
  • target (param.Parameterized) – The target object of the link.

  • callbacks (dict | None) – Maps from a parameter in the source object to a callback.

  • bidirectional (bool) – Whether to link source and target bi-directionally

  • **links (dict) – Maps between parameters on this object to the parameters on the supplied object.

save(filename: str | os.PathLike | IO, title: Optional[str] = None, resources: bokeh.resources.Resources | None = None, template: str | jinja2.environment.Template | None = None, template_variables: Dict[str, Any] = {}, embed: bool = False, max_states: int = 1000, max_opts: int = 3, embed_json: bool = False, json_prefix: str = '', save_path: str = './', load_path: Optional[str] = None, progress: bool = True, embed_states: Dict[Any, Any] = {}, as_png: bool | None = None, **kwargs) β†’ None[source]#

Saves Panel objects to file.

Parameters:
  • filename (str or file-like object) – Filename to save the plot to

  • title (string) – Optional title for the plot

  • resources (bokeh resources) – One of the valid bokeh.resources (e.g. CDN or INLINE)

  • template – passed to underlying io.save

  • template_variables – passed to underlying io.save

  • embed (bool) – Whether the state space should be embedded in the saved file.

  • max_states (int) – The maximum number of states to embed

  • max_opts (int) – The maximum number of states for a single widget

  • embed_json (boolean (default=True)) – Whether to export the data to json files

  • json_prefix (str (default='')) – Prefix for the auto-generated json directory

  • save_path (str (default='./')) – The path to save json files to

  • load_path (str (default=None)) – The path or URL the json files will be loaded from.

  • progress (boolean (default=True)) – Whether to report progress

  • embed_states (dict (default={})) – A dictionary specifying the widget values to embed for each widget

  • as_png (boolean (default=None)) – To save as a .png. If None save_png will be true if filename is string and ends with png.

select(selector: Optional[Union[type, Callable[[Viewable], bool]]] = None) β†’ List[Viewable][source]#

Iterates over the Viewable and any potential children in the applying the Selector.

Parameters:

selector (type or callable or None) – The selector allows selecting a subset of Viewables by declaring a type or callable function to filter by.

Returns:

viewables

Return type:

list(Viewable)

servable(title: Optional[str] = None, location: bool | 'Location' = True, area: str = 'main', target: Optional[str] = None) β†’ ServableMixin[source]#

Serves the object or adds it to the configured pn.state.template if in a panel serve context, writes to the DOM if in a pyodide context and returns the Panel object to allow it to display itself in a notebook context.

Parameters:
  • title (str) – A string title to give the Document (if served as an app)

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

  • area (str (deprecated)) – The area of a template to add the component too. Only has an effect if pn.config.template has been set.

  • target (str) – Target area to write to. If a template has been configured on pn.config.template this refers to the target area in the template while in pyodide this refers to the ID of the DOM node to write to.

Return type:

The Panel object itself

server_doc(doc: Optional[Document] = None, title: Optional[str] = None, location: bool | 'Location' = True) β†’ Document[source]#

Returns a serveable bokeh Document with the panel attached

Parameters:
  • doc (bokeh.Document (optional)) – The bokeh Document to attach the panel to as a root, defaults to bokeh.io.curdoc()

  • title (str) – A string title to give the Document

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

Returns:

doc – The bokeh document the panel was attached to

Return type:

bokeh.Document

show(title: Optional[str] = None, port: int = 0, address: Optional[str] = None, websocket_origin: Optional[str] = None, threaded: bool = False, verbose: bool = True, open: bool = True, location: bool | 'Location' = True, **kwargs) β†’ StoppableThread' | 'Server[source]#

Starts a Bokeh server and displays the Viewable in a new tab.

Parameters:
  • title (str | None) – A string title to give the Document (if served as an app)

  • port (int (optional, default=0)) – Allows specifying a specific port

  • address (str) – The address the server should listen on for HTTP requests.

  • websocket_origin (str or list(str) (optional)) – A list of hosts that can connect to the websocket. This is typically required when embedding a server app in an external web site. If None, β€œlocalhost” is used.

  • threaded (boolean (optional, default=False)) – Whether to launch the Server on a separate thread, allowing interactive use.

  • verbose (boolean (optional, default=True)) – Whether to print the address and port

  • open (boolean (optional, default=True)) – Whether to open the server in a new browser tab

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

Returns:

server – Returns the Bokeh server instance or the thread the server was launched on (if threaded=True)

Return type:

bokeh.server.Server or panel.io.server.StoppableThread

class panel.reactive.ReactiveData(*, selection, loading, align, aspect_ratio, css_classes, design, height, height_policy, margin, max_height, max_width, min_height, min_width, sizing_mode, styles, stylesheets, tags, visible, width, width_policy, name)[source]#

Bases: SyncableData

An extension of SyncableData which bi-directionally syncs a data parameter between frontend and backend using a ColumnDataSource.

Parameters inherited from:

panel.viewable.Layoutable: align, aspect_ratio, css_classes, design, height, min_width, min_height, max_width, max_height, margin, styles, stylesheets, tags, width, width_policy, height_policy, sizing_mode, visible

panel.viewable.Viewable: loading

panel.reactive.SyncableData: selection

clone(**params) β†’ Viewable[source]#

Makes a copy of the object sharing the same parameters.

Parameters:

params (Keyword arguments override the parameters on the clone.) –

Return type:

Cloned Viewable object

controls(parameters: List[str] = [], jslink: bool = True, **kwargs) β†’ Panel[source]#

Creates a set of widgets which allow manipulating the parameters on this instance. By default all parameters which support linking are exposed, but an explicit list of parameters can be provided.

Parameters:
  • parameters (list(str)) – An explicit list of parameters to return controls for.

  • jslink (bool) – Whether to use jslinks instead of Python based links. This does not allow using all types of parameters.

  • kwargs (dict) – Additional kwargs to pass to the Param pane(s) used to generate the controls widgets.

Return type:

A layout of the controls

embed(max_states: int = 1000, max_opts: int = 3, json: bool = False, json_prefix: str = '', save_path: str = './', load_path: Optional[str] = None, progress: bool = False, states={}) β†’ None[source]#

Renders a static version of a panel in a notebook by evaluating the set of states defined by the widgets in the model. Note this will only work well for simple apps with a relatively small state space.

Parameters:
  • max_states (int) – The maximum number of states to embed

  • max_opts (int) – The maximum number of states for a single widget

  • json (boolean (default=True)) – Whether to export the data to json files

  • json_prefix (str (default='')) – Prefix for JSON filename

  • save_path (str (default='./')) – The path to save json files to

  • load_path (str (default=None)) – The path or URL the json files will be loaded from.

  • progress (boolean (default=False)) – Whether to report progress

  • states (dict (default={})) – A dictionary specifying the widget values to embed for each widget

get_root(doc: Optional[Document] = None, comm: Optional[Comm] = None, preprocess: bool = True) β†’ Model[source]#

Returns the root model and applies pre-processing hooks

Parameters:
  • doc (bokeh.Document) – Bokeh document the bokeh model will be attached to.

  • comm (pyviz_comms.Comm) – Optional pyviz_comms when working in notebook

  • preprocess (boolean (default=True)) – Whether to run preprocessing hooks

Return type:

Returns the bokeh model corresponding to this panel object

jscallback(args: Dict[str, Any] = {}, **callbacks: str) β†’ Callback[source]#

Allows defining a JS callback to be triggered when a property changes on the source object. The keyword arguments define the properties that trigger a callback and the JS code that gets executed.

Parameters:
  • args (dict) – A mapping of objects to make available to the JS callback

  • **callbacks (dict) – A mapping between properties on the source model and the code to execute when that property changes

Returns:

callback – The Callback which can be used to disable the callback.

Return type:

Callback

Links properties on the this Reactive object to those on the target Reactive object in JS code.

Supports two modes, either specify a mapping between the source and target model properties as keywords or provide a dictionary of JS code snippets which maps from the source parameter to a JS code snippet which is executed when the property changes.

Parameters:
  • target (panel.viewable.Viewable | bokeh.model.Model | holoviews.core.dimension.Dimensioned) – The target to link the value to.

  • code (dict) – Custom code which will be executed when the widget value changes.

  • args (dict) – A mapping of objects to make available to the JS callback

  • bidirectional (boolean) – Whether to link source and target bi-directionally

  • **links (dict) – A mapping between properties on the source model and the target model property to link it to.

Returns:

link – The GenericLink which can be used unlink the widget and the target model.

Return type:

GenericLink

Links the parameters on this Reactive object to attributes on the target Parameterized object.

Supports two modes, either specify a mapping between the source and target object parameters as keywords or provide a dictionary of callbacks which maps from the source parameter to a callback which is triggered when the parameter changes.

Parameters:
  • target (param.Parameterized) – The target object of the link.

  • callbacks (dict | None) – Maps from a parameter in the source object to a callback.

  • bidirectional (bool) – Whether to link source and target bi-directionally

  • **links (dict) – Maps between parameters on this object to the parameters on the supplied object.

patch(patch_value: 'pd.DataFrame' | 'pd.Series' | Dict) β†’ None[source]#

Efficiently patches (updates) the existing value with the patch_value.

Parameters:

patch_value ((pd.DataFrame | pd.Series | Dict)) – The value(s) to patch the existing value with.

Raises:

ValueError – Raised if the patch_value is not a supported type.:

Examples

Patch a DataFrame with a Dictionary row. >>> value = pd.DataFrame({β€œx”: [1, 2], β€œy”: [β€œa”, β€œb”]}) >>> obj = DataComponent(value) >>> patch_value = {β€œx”: [(0, 3)]} >>> obj.patch(patch_value) >>> obj.value.to_dict(β€œlist”) {β€˜x’: [3, 2], β€˜y’: [β€˜a’, β€˜b’]}

Patch a Dataframe with a Dictionary of Columns. >>> value = pd.DataFrame({β€œx”: [1, 2], β€œy”: [β€œa”, β€œb”]}) >>> obj = DataComponent(value) >>> patch_value = {β€œx”: [(slice(2), (3,4))], β€œy”: [(1,’d’)]} >>> obj.patch(patch_value) >>> obj.value.to_dict(β€œlist”) {β€˜x’: [3, 4], β€˜y’: [β€˜a’, β€˜d’]}

Patch a DataFrame with a Series. Please note the index is used in the update. >>> value = pd.DataFrame({β€œx”: [1, 2], β€œy”: [β€œa”, β€œb”]}) >>> obj = DataComponent(value) >>> patch_value = pd.Series({β€œindex”: 1, β€œx”: 4, β€œy”: β€œd”}) >>> obj.patch(patch_value) >>> obj.value.to_dict(β€œlist”) {β€˜x’: [1, 4], β€˜y’: [β€˜a’, β€˜d’]}

Patch a Dataframe with a Dataframe. Please note the index is used in the update. >>> value = pd.DataFrame({β€œx”: [1, 2], β€œy”: [β€œa”, β€œb”]}) >>> obj = DataComponent(value) >>> patch_value = pd.DataFrame({β€œx”: [3, 4], β€œy”: [β€œc”, β€œd”]}) >>> obj.patch(patch_value) >>> obj.value.to_dict(β€œlist”) {β€˜x’: [3, 4], β€˜y’: [β€˜c’, β€˜d’]}

save(filename: str | os.PathLike | IO, title: Optional[str] = None, resources: bokeh.resources.Resources | None = None, template: str | jinja2.environment.Template | None = None, template_variables: Dict[str, Any] = {}, embed: bool = False, max_states: int = 1000, max_opts: int = 3, embed_json: bool = False, json_prefix: str = '', save_path: str = './', load_path: Optional[str] = None, progress: bool = True, embed_states: Dict[Any, Any] = {}, as_png: bool | None = None, **kwargs) β†’ None[source]#

Saves Panel objects to file.

Parameters:
  • filename (str or file-like object) – Filename to save the plot to

  • title (string) – Optional title for the plot

  • resources (bokeh resources) – One of the valid bokeh.resources (e.g. CDN or INLINE)

  • template – passed to underlying io.save

  • template_variables – passed to underlying io.save

  • embed (bool) – Whether the state space should be embedded in the saved file.

  • max_states (int) – The maximum number of states to embed

  • max_opts (int) – The maximum number of states for a single widget

  • embed_json (boolean (default=True)) – Whether to export the data to json files

  • json_prefix (str (default='')) – Prefix for the auto-generated json directory

  • save_path (str (default='./')) – The path to save json files to

  • load_path (str (default=None)) – The path or URL the json files will be loaded from.

  • progress (boolean (default=True)) – Whether to report progress

  • embed_states (dict (default={})) – A dictionary specifying the widget values to embed for each widget

  • as_png (boolean (default=None)) – To save as a .png. If None save_png will be true if filename is string and ends with png.

select(selector: Optional[Union[type, Callable[[Viewable], bool]]] = None) β†’ List[Viewable][source]#

Iterates over the Viewable and any potential children in the applying the Selector.

Parameters:

selector (type or callable or None) – The selector allows selecting a subset of Viewables by declaring a type or callable function to filter by.

Returns:

viewables

Return type:

list(Viewable)

servable(title: Optional[str] = None, location: bool | 'Location' = True, area: str = 'main', target: Optional[str] = None) β†’ ServableMixin[source]#

Serves the object or adds it to the configured pn.state.template if in a panel serve context, writes to the DOM if in a pyodide context and returns the Panel object to allow it to display itself in a notebook context.

Parameters:
  • title (str) – A string title to give the Document (if served as an app)

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

  • area (str (deprecated)) – The area of a template to add the component too. Only has an effect if pn.config.template has been set.

  • target (str) – Target area to write to. If a template has been configured on pn.config.template this refers to the target area in the template while in pyodide this refers to the ID of the DOM node to write to.

Return type:

The Panel object itself

server_doc(doc: Optional[Document] = None, title: Optional[str] = None, location: bool | 'Location' = True) β†’ Document[source]#

Returns a serveable bokeh Document with the panel attached

Parameters:
  • doc (bokeh.Document (optional)) – The bokeh Document to attach the panel to as a root, defaults to bokeh.io.curdoc()

  • title (str) – A string title to give the Document

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

Returns:

doc – The bokeh document the panel was attached to

Return type:

bokeh.Document

show(title: Optional[str] = None, port: int = 0, address: Optional[str] = None, websocket_origin: Optional[str] = None, threaded: bool = False, verbose: bool = True, open: bool = True, location: bool | 'Location' = True, **kwargs) β†’ StoppableThread' | 'Server[source]#

Starts a Bokeh server and displays the Viewable in a new tab.

Parameters:
  • title (str | None) – A string title to give the Document (if served as an app)

  • port (int (optional, default=0)) – Allows specifying a specific port

  • address (str) – The address the server should listen on for HTTP requests.

  • websocket_origin (str or list(str) (optional)) – A list of hosts that can connect to the websocket. This is typically required when embedding a server app in an external web site. If None, β€œlocalhost” is used.

  • threaded (boolean (optional, default=False)) – Whether to launch the Server on a separate thread, allowing interactive use.

  • verbose (boolean (optional, default=True)) – Whether to print the address and port

  • open (boolean (optional, default=True)) – Whether to open the server in a new browser tab

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

Returns:

server – Returns the Bokeh server instance or the thread the server was launched on (if threaded=True)

Return type:

bokeh.server.Server or panel.io.server.StoppableThread

stream(stream_value: 'pd.DataFrame' | 'pd.Series' | Dict, rollover: Optional[int] = None, reset_index: bool = True) β†’ None[source]#

Streams (appends) the stream_value provided to the existing value in an efficient manner.

Parameters:
  • stream_value ((pd.DataFrame | pd.Series | Dict)) – The new value(s) to append to the existing value.

  • rollover ((int | None, default=None)) – A maximum column size, above which data from the start of the column begins to be discarded. If None, then columns will continue to grow unbounded.

  • (bool (reset_index) – If True and the stream_value is a DataFrame, then its index is reset. Helps to keep the index unique and named index.

  • default=True) – If True and the stream_value is a DataFrame, then its index is reset. Helps to keep the index unique and named index.

Raises:

ValueError – Raised if the stream_value is not a supported type.:

Examples

Stream a Series to a DataFrame >>> value = pd.DataFrame({β€œx”: [1, 2], β€œy”: [β€œa”, β€œb”]}) >>> obj = DataComponent(value) >>> stream_value = pd.Series({β€œx”: 4, β€œy”: β€œd”}) >>> obj.stream(stream_value) >>> obj.value.to_dict(β€œlist”) {β€˜x’: [1, 2, 4], β€˜y’: [β€˜a’, β€˜b’, β€˜d’]}

Stream a Dataframe to a Dataframe >>> value = pd.DataFrame({β€œx”: [1, 2], β€œy”: [β€œa”, β€œb”]}) >>> obj = DataComponent(value) >>> stream_value = pd.DataFrame({β€œx”: [3, 4], β€œy”: [β€œc”, β€œd”]}) >>> obj.stream(stream_value) >>> obj.value.to_dict(β€œlist”) {β€˜x’: [1, 2, 3, 4], β€˜y’: [β€˜a’, β€˜b’, β€˜c’, β€˜d’]}

Stream a Dictionary row to a DataFrame >>> value = pd.DataFrame({β€œx”: [1, 2], β€œy”: [β€œa”, β€œb”]}) >>> tabulator = DataComponent(value) >>> stream_value = {β€œx”: 4, β€œy”: β€œd”} >>> obj.stream(stream_value) >>> obj.value.to_dict(β€œlist”) {β€˜x’: [1, 2, 4], β€˜y’: [β€˜a’, β€˜b’, β€˜d’]}

Stream a Dictionary of Columns to a Dataframe >>> value = pd.DataFrame({β€œx”: [1, 2], β€œy”: [β€œa”, β€œb”]}) >>> obj = DataComponent(value) >>> stream_value = {β€œx”: [3, 4], β€œy”: [β€œc”, β€œd”]} >>> obj.stream(stream_value) >>> obj.value.to_dict(β€œlist”) {β€˜x’: [1, 2, 3, 4], β€˜y’: [β€˜a’, β€˜b’, β€˜c’, β€˜d’]}

class panel.reactive.ReactiveHTML(*, loading, align, aspect_ratio, css_classes, design, height, height_policy, margin, max_height, max_width, min_height, min_width, sizing_mode, styles, stylesheets, tags, visible, width, width_policy, name)[source]#

Bases: Reactive

The ReactiveHTML class enables you to create custom Panel components using HTML, CSS and/ or Javascript and without the complexities of Javascript build tools.

A ReactiveHTML subclass provides bi-directional syncing of its parameters with arbitrary HTML elements, attributes and properties. The key part of the subclass is the _template variable. This is the HTML template that gets rendered and declares how to link parameters on the subclass to HTML.

>>>    import panel as pn
>>>    import param
>>>    class CustomComponent(pn.reactive.ReactiveHTML):
...
...        index = param.Integer(default=0)
...
...        _template = '<img id="slideshow" src="https://picsum.photos/800/300?image=${index}" onclick="${_img_click}"></img>'
...
...        def _img_click(self, event):
...            self.index += 1
>>>    CustomComponent(width=500, height=200).servable()

HTML templates#

A ReactiveHTML component is declared by providing an HTML template on the _template attribute on the class. Parameters are synced by inserting them as template variables of the form ${parameter_name}, e.g.:

<div class=”${parameter_1}”>${parameter_2}</div>

will interpolate the parameter1 parameter on the class. In addition to providing attributes we can also provide children to an HTML tag. By default any parameter referenced as a child will be treated as a Panel components to be rendered into the containing HTML. This makes it possible to use ReactiveHTML to lay out other components.

Children#

As mentioned above parameters may be referenced as children of a DOM node and will, by default, be treated as Panel components to insert on the DOM node. However by declaring a _child_config we can control how the DOM nodes are treated. The _child_config is indexed by parameter name and may declare one of three rendering modes:

  • model (default): Create child and render child as a Panel component into it.

  • literal: Create child and set child as its innerHTML.

  • template: Set child as innerHTML of the container.

If the type is β€˜template’ the parameter will be inserted as is and the DOM node’s innerHTML will be synced with the child parameter.

DOM Events#

In certain cases it is necessary to explicitly declare event listeners on the DOM node to ensure that changes in their properties are synced when an event is fired. To make this possible the HTML element in question must be given a unique id, e.g.:

<input id=”input_el”></input>

Now we can use this name to declare set of _dom_events to subscribe to. The following will subscribe to change DOM events on the input element:

{β€˜input_el’: [β€˜change’]}

Once subscribed the class may also define a method following the _{node}_{event} naming convention which will fire when the DOM event triggers, e.g. we could define a _input_el_change method. Any such callback will be given a DOMEvent object as the first and only argument. The DOMEvent contains information about the event on the .data attribute and declares the type of event on the .type attribute.

Inline callbacks#

Instead of declaring explicit DOM events Python callbacks can also be declared inline, e.g.:

<input id=”input_el” onchange=”${_input_change}”></input>

will look for an _input_change method on the ReactiveHTML component and call it when the event is fired.

Additionally we can invoke pure JS scripts defined on the class, e.g.:

<input id=”input_el” onchange=”${script(β€˜some_script’)}”></input>

This will invoke the following script if it is defined on the class:

_scripts = {

β€˜some_script’: β€˜console.log(model, data, input_el, view)’

}

Scripts#

In addition to declaring callbacks in Python it is also possible to declare Javascript callbacks to execute when any synced attribute changes. Let us say we have declared an input element with a synced value parameter:

<input id=”input_el” value=”${value}”></input>

We can now declare a set of _scripts, which will fire whenever the value updates:

_scripts = {

β€˜value’: β€˜console.log(model, data, input_el)’

}

The Javascript is provided multiple objects in its namespace including:

  • dataThe data model holds the current values of the synced

    parameters, e.g. data.value will reflect the current value of the input_el node.

  • model: The ReactiveHTML model which holds layout information

    and information about the children and events.

  • state: An empty state dictionary which scripts can use to

    store state for the lifetime of the view.

  • view: The Bokeh View class responsible for rendering the

    component. This provides access to method like invalidate_layout and run_script which allows invoking other scripts.

  • <node>: All named DOM nodes in the HTML template, e.g. the

    input_el node in the example above.

Parameters inherited from:

panel.viewable.Layoutable: align, aspect_ratio, css_classes, design, height, min_width, min_height, max_width, max_height, margin, styles, stylesheets, tags, width, width_policy, height_policy, sizing_mode, visible

panel.viewable.Viewable: loading

clone(**params) β†’ Viewable[source]#

Makes a copy of the object sharing the same parameters.

Parameters:

params (Keyword arguments override the parameters on the clone.) –

Return type:

Cloned Viewable object

controls(parameters: List[str] = [], jslink: bool = True, **kwargs) β†’ Panel[source]#

Creates a set of widgets which allow manipulating the parameters on this instance. By default all parameters which support linking are exposed, but an explicit list of parameters can be provided.

Parameters:
  • parameters (list(str)) – An explicit list of parameters to return controls for.

  • jslink (bool) – Whether to use jslinks instead of Python based links. This does not allow using all types of parameters.

  • kwargs (dict) – Additional kwargs to pass to the Param pane(s) used to generate the controls widgets.

Return type:

A layout of the controls

embed(max_states: int = 1000, max_opts: int = 3, json: bool = False, json_prefix: str = '', save_path: str = './', load_path: Optional[str] = None, progress: bool = False, states={}) β†’ None[source]#

Renders a static version of a panel in a notebook by evaluating the set of states defined by the widgets in the model. Note this will only work well for simple apps with a relatively small state space.

Parameters:
  • max_states (int) – The maximum number of states to embed

  • max_opts (int) – The maximum number of states for a single widget

  • json (boolean (default=True)) – Whether to export the data to json files

  • json_prefix (str (default='')) – Prefix for JSON filename

  • save_path (str (default='./')) – The path to save json files to

  • load_path (str (default=None)) – The path or URL the json files will be loaded from.

  • progress (boolean (default=False)) – Whether to report progress

  • states (dict (default={})) – A dictionary specifying the widget values to embed for each widget

get_root(doc: Optional[Document] = None, comm: Optional[Comm] = None, preprocess: bool = True) β†’ Model[source]#

Returns the root model and applies pre-processing hooks

Parameters:
  • doc (bokeh.Document) – Bokeh document the bokeh model will be attached to.

  • comm (pyviz_comms.Comm) – Optional pyviz_comms when working in notebook

  • preprocess (boolean (default=True)) – Whether to run preprocessing hooks

Return type:

Returns the bokeh model corresponding to this panel object

jscallback(args: Dict[str, Any] = {}, **callbacks: str) β†’ Callback[source]#

Allows defining a JS callback to be triggered when a property changes on the source object. The keyword arguments define the properties that trigger a callback and the JS code that gets executed.

Parameters:
  • args (dict) – A mapping of objects to make available to the JS callback

  • **callbacks (dict) – A mapping between properties on the source model and the code to execute when that property changes

Returns:

callback – The Callback which can be used to disable the callback.

Return type:

Callback

Links properties on the this Reactive object to those on the target Reactive object in JS code.

Supports two modes, either specify a mapping between the source and target model properties as keywords or provide a dictionary of JS code snippets which maps from the source parameter to a JS code snippet which is executed when the property changes.

Parameters:
  • target (panel.viewable.Viewable | bokeh.model.Model | holoviews.core.dimension.Dimensioned) – The target to link the value to.

  • code (dict) – Custom code which will be executed when the widget value changes.

  • args (dict) – A mapping of objects to make available to the JS callback

  • bidirectional (boolean) – Whether to link source and target bi-directionally

  • **links (dict) – A mapping between properties on the source model and the target model property to link it to.

Returns:

link – The GenericLink which can be used unlink the widget and the target model.

Return type:

GenericLink

Links the parameters on this Reactive object to attributes on the target Parameterized object.

Supports two modes, either specify a mapping between the source and target object parameters as keywords or provide a dictionary of callbacks which maps from the source parameter to a callback which is triggered when the parameter changes.

Parameters:
  • target (param.Parameterized) – The target object of the link.

  • callbacks (dict | None) – Maps from a parameter in the source object to a callback.

  • bidirectional (bool) – Whether to link source and target bi-directionally

  • **links (dict) – Maps between parameters on this object to the parameters on the supplied object.

on_event(node: str, event: str, callback: Callable) β†’ None[source]#

Registers a callback to be executed when the specified DOM event is triggered on the named node. Note that the named node must be declared in the HTML. To create a named node you must give it an id of the form id=”name”, where name will be the node identifier.

Parameters:
  • node (str) – Named node in the HTML identifiable via id of the form id=”name”.

  • event (str) – Name of the DOM event to add an event listener to.

  • callback (callable) – A callable which will be given the DOMEvent object.

save(filename: str | os.PathLike | IO, title: Optional[str] = None, resources: bokeh.resources.Resources | None = None, template: str | jinja2.environment.Template | None = None, template_variables: Dict[str, Any] = {}, embed: bool = False, max_states: int = 1000, max_opts: int = 3, embed_json: bool = False, json_prefix: str = '', save_path: str = './', load_path: Optional[str] = None, progress: bool = True, embed_states: Dict[Any, Any] = {}, as_png: bool | None = None, **kwargs) β†’ None[source]#

Saves Panel objects to file.

Parameters:
  • filename (str or file-like object) – Filename to save the plot to

  • title (string) – Optional title for the plot

  • resources (bokeh resources) – One of the valid bokeh.resources (e.g. CDN or INLINE)

  • template – passed to underlying io.save

  • template_variables – passed to underlying io.save

  • embed (bool) – Whether the state space should be embedded in the saved file.

  • max_states (int) – The maximum number of states to embed

  • max_opts (int) – The maximum number of states for a single widget

  • embed_json (boolean (default=True)) – Whether to export the data to json files

  • json_prefix (str (default='')) – Prefix for the auto-generated json directory

  • save_path (str (default='./')) – The path to save json files to

  • load_path (str (default=None)) – The path or URL the json files will be loaded from.

  • progress (boolean (default=True)) – Whether to report progress

  • embed_states (dict (default={})) – A dictionary specifying the widget values to embed for each widget

  • as_png (boolean (default=None)) – To save as a .png. If None save_png will be true if filename is string and ends with png.

select(selector: Optional[Union[type, Callable[[Viewable], bool]]] = None) β†’ List[Viewable][source]#

Iterates over the Viewable and any potential children in the applying the Selector.

Parameters:

selector (type or callable or None) – The selector allows selecting a subset of Viewables by declaring a type or callable function to filter by.

Returns:

viewables

Return type:

list(Viewable)

servable(title: Optional[str] = None, location: bool | 'Location' = True, area: str = 'main', target: Optional[str] = None) β†’ ServableMixin[source]#

Serves the object or adds it to the configured pn.state.template if in a panel serve context, writes to the DOM if in a pyodide context and returns the Panel object to allow it to display itself in a notebook context.

Parameters:
  • title (str) – A string title to give the Document (if served as an app)

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

  • area (str (deprecated)) – The area of a template to add the component too. Only has an effect if pn.config.template has been set.

  • target (str) – Target area to write to. If a template has been configured on pn.config.template this refers to the target area in the template while in pyodide this refers to the ID of the DOM node to write to.

Return type:

The Panel object itself

server_doc(doc: Optional[Document] = None, title: Optional[str] = None, location: bool | 'Location' = True) β†’ Document[source]#

Returns a serveable bokeh Document with the panel attached

Parameters:
  • doc (bokeh.Document (optional)) – The bokeh Document to attach the panel to as a root, defaults to bokeh.io.curdoc()

  • title (str) – A string title to give the Document

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

Returns:

doc – The bokeh document the panel was attached to

Return type:

bokeh.Document

show(title: Optional[str] = None, port: int = 0, address: Optional[str] = None, websocket_origin: Optional[str] = None, threaded: bool = False, verbose: bool = True, open: bool = True, location: bool | 'Location' = True, **kwargs) β†’ StoppableThread' | 'Server[source]#

Starts a Bokeh server and displays the Viewable in a new tab.

Parameters:
  • title (str | None) – A string title to give the Document (if served as an app)

  • port (int (optional, default=0)) – Allows specifying a specific port

  • address (str) – The address the server should listen on for HTTP requests.

  • websocket_origin (str or list(str) (optional)) – A list of hosts that can connect to the websocket. This is typically required when embedding a server app in an external web site. If None, β€œlocalhost” is used.

  • threaded (boolean (optional, default=False)) – Whether to launch the Server on a separate thread, allowing interactive use.

  • verbose (boolean (optional, default=True)) – Whether to print the address and port

  • open (boolean (optional, default=True)) – Whether to open the server in a new browser tab

  • location (boolean or panel.io.location.Location) – Whether to create a Location component to observe and set the URL location.

Returns:

server – Returns the Bokeh server instance or the thread the server was launched on (if threaded=True)

Return type:

bokeh.server.Server or panel.io.server.StoppableThread