plotly dash: create multiple callbacks (with loop?)

In dash >= 1.11.0 you may use Pattern-Matching Callbacks. No loops needed when defining the callback(s).

Example

1. Import callback selectors

  • Import dash.dependecies.ALL:
from dash.dependencies import Input, Output, State, ALL
  • Other available callback selectors are MATCH and ALLSMALLER.

2. Use dictionaries as the id

  • Define your components with a id that is a dictionary. You may choose any keys but for example type and id are quite reasonable choices. So, instead of
[dcc.Input(type = 'number', id = 'input %i'%i) for i in range(20)]

use

[
    dcc.Input(type='number',
              id={
                  'type': 'my-input-type',
                  'id': 'input %i' % i
              }) for i in range(20)
]

3. Use a callback selector with @app.callback

  • Use the ALL callback selector when defining the callback:
@app.callback(
    dash.dependencies.Output({
        'type': 'my-input-type',
        'id': ALL
    }, 'value'), [dash.dependencies.Input('button populate', 'n_clicks')])
def update(ignore):
    return np.random.uniform()

I have dealt with the same issue and found a solution. What you do is bypass the decorator and call the app.callback function directly:

def update(ignore):
    return np.random.uniform()

for i in range(20):
    app.callback(
        dash.dependencies.Output('input %i' % i, 'value'),
        [dash.dependencies.Input('button populate', 'n_clicks')]
    )(update)

Tags:

Plotly Dash