3

In a single-page Dash by Plotly app I want to show many similar graphs.

For this I have created a "factory class" which can generate many graphs.

This class exposes methods to be used in the Dash app's app.layout and @app.callback code. A sample app.py with two graphs looks like this:

import ...

app = dash.Dash(__name__)

graph_A = GraphFactory(feature="A")
graph_B = GraphFactory(feature="B")

app.layout = html.Div([
            graph_A.graph(),
            graph_B.graph(),
            ])

@app.callback(
    graph_A.callback_output(), graph_A.callback_inputs()
)
def update_A(value):
    return graph_A.callback_update(value)

@app.callback(
    graph_B.callback_output(), graph_B.callback_inputs()
)
def update_B(value):
    return graph_B.callback_update(value)

This works fine. However I want to display many graphs from a list of GraphFactory objects. It's easy to create the objects and put them in the app layout:

graph_list = [ GraphFactory(feature=f) for f in feature_list ]

app.layout = html.Div([ 
            g.graph() for g in graph_list
            ])

But **how can I add the many callback_output(), callback_inputs() and callback_update(value) calls? Is there a way to write the decorator and the function only once and add the calls to the callback_... functions in there?

halloleo
  • 9,216
  • 13
  • 64
  • 122

2 Answers2

4

By digging into decorators I found a solution myself: You can call the Dash decorator on the object's callback_update function directly. So for the example from the question you can write:

for g in graph_list:
    dash_app.callback(g.callback_output(),
                      g.callback_inputs())(g.callback_update)

Please note carefully, that g.callback_update has no (), because the app.callback function is applied to the g.callback_update function/method, not as usual to its return value.

halloleo
  • 9,216
  • 13
  • 64
  • 122
0

In case anyone else looks for another way of doing this, a solution was introduced in Dash 0.39 - Multiple Outputs.

https://community.plotly.com/t/multiple-outputs-in-dash-now-available/19437

Use a list/tuple of Output as output in callbacks. Return a tuple/list of value from the callbacks The returned list must have the same length as the list of output The output props are applied in the order they were declared in the output > list.

'Applied' = outputs declared in callback applied in app.layout in order from top to bottom

ivanp
  • 340
  • 1
  • 5