Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Document pn.bind in API user guide #1973

Merged
merged 2 commits into from
Feb 12, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 89 additions & 19 deletions examples/user_guide/APIs.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
"Panel can be used to make a first pass at an app or dashboard in minutes, while also allowing you to fully customize the app's behavior and appearance or flexibly integrate GUI support into long-term, large-scale software projects. To accommodate these different ways of using Panel, four different APIs are available:\n",
"\n",
"* **Interact functions**: Auto-generates a full UI (including widgets) given a function\n",
"* **Reactive functions**: Linking functions or methods to widgets using the ``pn.depends`` decorator, declaring that the function should be re-run when those widget values change\n",
"* **Reactive functions**: Linking functions or methods to widgets using ``pn.bind`` or the equivalent ``pn.depends`` decorator, declaring that the function should be re-run when those widget values change\n",
"* **Parameterized class**: Declare parameters and their ranges in Parameterized classes, then get GUIs (and value checking!) for free\n",
"* **Callbacks**: Generate a UI by manually declaring callbacks that update panels or panes\n",
"\n",
Expand Down Expand Up @@ -70,21 +70,21 @@
"source": [
"## Interact Functions\n",
"\n",
"The ``interact`` function will automatically generate a UI (including widgets) by inspecting the arguments of the function given to it, or by using additional hints you provide in the ``interact`` function call. If you have worked with the [``ipywidgets``](https://github.com/jupyter-widgets/ipywidgets) package you may already be familiar with this approach (in fact the implementation is modeled on that reference implementation). The basic idea is that given a function that returns some object, Panel will inspect the arguments to that function, try to infer appropriate widgets for those arguments, and then re-run that function to update the output whenever one of the widgets generates an event. For more detail on how interact creates widgets and other ways of using it, see the Panel [interact user guide](./interact.ipynb). This section instead focuses on when and why to use this API, laying out its benefits and drawbacks.\n",
"The ``interact`` function will automatically generate a UI (including widgets) by inspecting the arguments of the function given to it, or by using additional hints you provide in the ``interact`` function call. If you have worked with the [``ipywidgets``](https://github.com/jupyter-widgets/ipywidgets) package you may already be familiar with this approach. (In fact, the Panel interact function is modeled on the one from ipywidgets, making it simpler to port code between the two platforms.) The basic idea is that given a function that returns some object, Panel will inspect the arguments to that function, try to infer appropriate widgets for those arguments, and then re-run that function to update the output whenever one of the widgets generates an event. For more detail on how interact creates widgets and other ways of using it, see the Panel [interact user guide](./interact.ipynb). This section instead focuses on when and why to use this API, laying out its benefits and drawbacks.\n",
"\n",
"The main benefit of this approach is convenience and ease of use. You start by writing some function that returns an object, be that a plot, a dataframe, or anything else that Panel can render. Then with a single call to `pn.interact()`, you can immediately get an interactive UI. Unlike ipywidgets, the ``pn.interact`` call will return a Panel. This Panel can then be further modified by laying out the widgets and output separately, or combining these components with other panes. Even though `pn.interact` itself is limited in flexibility, you can unpack and reconfigure the results from it to generate fairly complex GUIs in very little code. \n",
"The main benefit of this approach is convenience and ease of use. You start by writing some function that returns an object, be that a plot, a dataframe, or anything else that Panel can render. Then with a single call to `pn.interact()`, you can immediately get an interactive UI, without ever instantiating any widgets or wiring up any callbacks explicitly. Unlike ipywidgets, the ``pn.interact`` call will return a Panel. This Panel can then be further modified by laying out the widgets and output separately, or combining these components with other panes. Even though `pn.interact` itself is limited in flexibility compared to the rest of Panel, you can still unpack and reconfigure the results from it to generate fairly complex GUIs in very little code. \n",
"\n",
"#### Pros:\n",
"\n",
"+ Easy to use.\n",
"+ Easy to use (or at least easy to get started!).\n",
"+ Doesn't typically require modifying existing visualization code.\n",
"\n",
"#### Cons:\n",
"\n",
"- Most of the behavior is implicit, with magic happening by introspection, making it difficult to see how to modify the appearance or functionality of the resulting object.\n",
"- Layouts can be customized, but require indexing into the panel returned by `interact`.\n",
"- Customizing the layout requires indexing into the panel returned by `interact`.\n",
"\n",
"In the example below, ``pn.interact`` infers the initial value for `x` and `y` from the `autompg_plot` function default arguments and their widget type and range from the `columns` list provided to `interact`. `interact` would have no way of knowing that a color picker would be useful for the `color` argument (as each color is simply a string), and so here we explicitly create a color-picker widget and pass that as the value for the color so that we can control the color as well. Finally, we unpack the result from `interact` and rearrange it in a different layout with a title, to create the final app. See the Panel [interact user guide](./interact.ipynb) for details about how to control the widgets and how to rearrange the layout."
"The simplest `interact` call can be a one-liner, but here we'll show an example of intermediate complexity so that you get a good idea of what `interact` can do in practice. In this code, ``pn.interact`` infers the initial value for `x` and `y` from the `autompg_plot` function default arguments and their widget type and range from the `columns` list provided to `interact`. `interact` wouldn't normally put up a color widget because it would have no way of knowing that this string-type argument represents an RGB color, and so here we explicitly create a color-picker widget and pass that as the value for the color so that we can control the color as well. Finally, we unpack the result from `interact` and rearrange it in a different layout with a title, to create the final app. See the Panel [interact user guide](./interact.ipynb) for even simpler examples along with details about how to control the widgets and how to rearrange the layout."
]
},
{
Expand All @@ -105,18 +105,59 @@
"source": [
"## Reactive Functions\n",
"\n",
"The reactive programming API is very similar to the ``interact`` function but makes it possible to explicitly declare the inputs to the function using the ``depends`` decorator. It also makes the layout of the different components more explicit. The ``pn.depends`` decorator is a powerful tool to declare the parameters a function depends on. By decorating a function with `pn.depends`, we declare that when we change these parameters the function should be called with their new values. This approach makes it explicit which parameters the function depends on and ties the function directly to the objects that control it. Once a function has been annotated in this way, it can be laid out alongside the widgets.\n",
"The `pn.bind` reactive programming API is very similar to the ``interact`` function but is more explicit about widget selection and layout. `pn.bind` requires the programmer to select and configure widgets explicity and to lay out components explicitly, without relying on inference of widget types and ranges and without any default layouts. Specifying those aspects explicitly provides more power and control, but does typically take a bit more code and more knowledge of widget and layout components than using `interact` does. Once widgets have been bound to a reactive function, you can lay out the bound function and the widgets in any order or combination you like, including across Jupyter notebook cells if desired.\n",
"\n",
"#### Pros:\n",
"\n",
"+ Very clear mapping from the inputs to the arguments of the function.\n",
"+ Very clear mapping from widgets to the arguments of the function.\n",
"+ Very explicit layout of each of the different components.\n",
"+ Like `interact`, doesn't typically require modifying existing visualization code.\n",
"\n",
"#### Cons:\n",
"\n",
"- Mixes the definition of the function with the GUI elements it depends on.\n",
"- Typically requires a bit more code than `interact`\n",
"\n",
"In this model, we declare all the widgets we will need first, then declare a function linked to those widgets using the ``pn.depends`` decorator, and finally lay out the widgets and the ``autompg_plot`` function explicitly."
"In this model, we can use an existing plotting function just as for `interact`, but then need to declare each widget explicitly and then bind a widget to each of the arguments that we want to be interactive. The `pn.bind` function works much like [`functools.partial`](https://docs.python.org/3/library/functools.html#functools.partial) in that it binds regular arguments and keyword arguments to a function. `partial` can only bind specific, static arguments like `5`, but `pn.bind` can also bind parameters, widgets, and other dynamic functions with dependencies to the arguments, ensuring when the function is called the current values of the parameters are passed to the function. A bound function is then reactive, updating whenever the widget values change.\n",
"\n",
"To make the concept of binding clear, let's look at a trivial example first:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def fn(a,b): return f'Arguments: {a,b}'\n",
"slider = pn.widgets.FloatSlider(value=0.5)\n",
"\n",
"bound_fn = pn.bind(fn, a=slider, b=2)\n",
"bound_fn()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Here we can see that although `fn` required two arguments, `bound_fn` takes no arguments because `a` has been bound to the slider value and `b` to a static value. \n",
"\n",
"If we display the slider and bound function in Panel, we can see that everything will update reactively as you use the widget, reevaluating the function whenever the bound argument changes:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"pn.Row(slider, bound_fn)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Using `pn.bind`, we can easily build something like the `interact` app above if we explicitly make widgets for each argument, bind them to the plotting function, and lay out the result with the widgets:"
]
},
{
Expand All @@ -129,13 +170,42 @@
"y = pn.widgets.Select(value='hp', options=columns, name='y')\n",
"color = pn.widgets.ColorPicker(name='Color', value='#AA0505')\n",
"\n",
"@pn.depends(x.param.value, y.param.value, color.param.value)\n",
"def autompg_plot(x, y, color):\n",
" return autompg.hvplot.scatter(x, y, c=color)\n",
"pn.Row(pn.Column('## MPG Explorer', x, y, color),\n",
" pn.bind(autompg.hvplot.scatter, x, y, c=color))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Notice how here we didn't even need the `autompg_plot` function here, because `bind` works with both methods and functions, so for this particular case the reactive API works out to the same amount of code as `interact`. In practice `interact` is shorter and simpler in the case of accepting the default behavior, making it simple to get started, while `pn.bind` requires a bit more code to get started but then allows easier customization and specification.\n",
"\n",
"pn.Row(\n",
" pn.Column('## MPG Explorer', x, y, color),\n",
" autompg_plot)"
"If you are writing code specifically for building an app, and do not wish to keep domain and GUI code separate, the functionality of `pn.bind` is also available as a decorator `@pn.depends`:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"x = pn.widgets.Select(value='mpg', options=columns, name='x')\n",
"y = pn.widgets.Select(value='hp', options=columns, name='y')\n",
"color = pn.widgets.ColorPicker(name='Color', value='#AA0505')\n",
"\n",
"@pn.depends(x, y, color)\n",
"def autompg_plot(xval, yval, colorval):\n",
" return autompg.hvplot.scatter(xval, yval, c=colorval)\n",
"\n",
"pn.Row(pn.Column('## MPG Explorer', x, y, color), \n",
" autompg_plot)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"This alternative way of specifying the same app lets you declare the dependency between a function argument and a widget (or parameter) from the start, which can be clearer if you know the function will always and only be used in a GUI. Otherwise, the `pn.bind` version is preferred, because it allows you to keep the Panel-specific code separate (even in a different Python module or file) from the underlying analysis and plotting code."
]
},
{
Expand All @@ -144,7 +214,7 @@
"source": [
"## Parameterized Classes\n",
"\n",
"The [Param](http://param.pyviz.org) library allows expressing the parameters of a class (or a hierarchy of classes) completely independently of a GUI implementation. Panel and other libraries can then take those parameter declarations and turn them into a GUI to control the parameters. This approach allows the parameters controlling some computation to be captured specifically and explicitly (but as abstract parameters, not as widgets). Then thanks to the ``param.depends`` decorator, it is then possible to directly express the dependencies between the parameters and the computation defined in some method on the class, all without ever importing Panel or any other GUI library. The resulting objects can then be used in both GUI and non-GUI contexts (batch computations, scripts, servers).\n",
"The [Param](http://param.pyviz.org) library allows expressing the parameters of a class (or a hierarchy of classes) completely independently of a GUI implementation. Panel and other libraries can then take those parameter declarations and turn them into a GUI to control the parameters. This approach allows the parameters controlling some computation to be captured specifically and explicitly (but as abstract parameters, not as widgets). Then thanks to the ``@param.depends`` decorator (similar to `@panel.depends` but for use in Parameterized classes without any dependency on Panel), it is then possible to directly express the dependencies between the parameters and the computation defined in some method on the class, all without ever importing Panel or any other GUI library. The resulting objects can then be used in both GUI and non-GUI contexts (batch computations, scripts, servers).\n",
"\n",
"The parameterized approach is a powerful way to encapsulate computation in self-contained classes, taking advantage of object-oriented programming patterns. It also makes it possible to express a problem completely independently from Panel or any other GUI code, while still getting a GUI for free as a last step. For more detail on using this approach see the [Param user guide](./Param.ipynb).\n",
"\n",
Expand Down Expand Up @@ -236,7 +306,7 @@
"source": [
"## Summary\n",
"\n",
"As we have seen, each of these four APIs allows building the same basic application. The choice of the appropriate API depends very much on the use case. To build a quick throwaway GUI the ``interact`` approach can be completely sufficient. A more more explicit, flexible, and maintainable version of that approach is to define a reactive function that links directly to a set of widgets. When writing libraries or other code that might be used independently of the actual GUI, a Parameterized class can be a great way to organize the code. Finally, if you need low-level control or want to complement any of the other approaches, defining explicit callbacks can be the best approach. Nearly all of the functionality of Panel can be accessed using any of the APIs, but each makes certain things much easier than others. Choosing the API is therefore a matter of considering the tradeoffs and of course also a matter of preference."
"As we have seen, each of these four APIs allows building the same basic application. The choice of the appropriate API depends very much on the use case. To build a quick throwaway GUI the ``interact`` approach can be completely sufficient. A more more explicit, flexible, and maintainable version of that approach is to define a reactive function that is bound directly to a set of widgets using `pn.bind`. When writing libraries or other code that might be used independently of the actual GUI, a Parameterized class can be a great way to organize the code. Finally, if you need low-level control or want to complement any of the other approaches, defining explicit callbacks can be the best approach. Nearly all of the functionality of Panel can be accessed using any of the APIs, but each makes certain things much easier than others. Choosing the API is therefore a matter of considering the tradeoffs and of course also a matter of preference. If you still aren't sure after reading the above, then just go with the `pn.bind` reactive API!"
]
}
],
Expand All @@ -248,4 +318,4 @@
},
"nbformat": 4,
"nbformat_minor": 2
}
}