Black Lives Matter. Please consider donating to Black Girls Code today.
Dash HoloViews is now available! Check out the docs.

Create callback inside a callback?

Is it possible to register a new callback while a server is already running:

app = dash.Dash()
app.config.suppress_callback_exceptions = True

app.layout = html.Div(children=[
    html.Button(
        'Add',
        id='add_button',
    ),
    html.Div(id='content'),
])

@app.callback(
    output=Output(component_id='content', component_property='children'),
    inputs=[
        Input(component_id='add_button', component_property='n_clicks'),
    ],
)
def pushed(n):
    if n is None:
        return html.Div()
    content = html.Div(
        id=f'clicked_{n}',
        children=[
            html.Button(
                f'Button_{n}',
                id=f'button_{n}'
            ),
            html.Div(id=f'content_{n}')
        ],
    ),

    print(f'making callback {n}')
    @app.callback(
        output=Output(component_id=f'content_{n}', component_property='children'),
        inputs=[
            Input(component_id=f'button_{n}', component_property='n_clicks')
        ]
    )
    def button_press(nc):
        print(f'callback {n}')
        return f'button {n} pushed {nc} times'
    
    return content

I’ve seen differing information about this. The above code doesn’t work, behaving as though the dynamically created callbacks don’t exist.

It’s not, see Dynamic Controls and Dynamic Output Components