dash-docs
dash-docs copied to clipboard
Document recommended approach for callback context and multiple inputs
i.e. using the callback like a router. It's basically the same amount of code as writing separate callbacks but without a proper example people are using long if or switch statements instead of refactoring their code. See e.g. https://github.com/plotly/dash/issues/850#issuecomment-690770129. Until we document recommended syntax, we'll get lots of pressure to provide a simpler way.
Copied from https://github.com/plotly/dash/issues/850#issuecomment-775185229
Here is a gist https://gist.github.com/nicolaskruchten/8aa6ae9df62d2c45ef87ad28efd06a31 that implements a simple "router" pattern for both cases listed above using dash.callback_context:
callback1(In_A, State) → Out_1 callback2(In_B, State) → Out_1
and
callback3(In_A, In_C, State) -> Out_2 callback4(In_B, In_C, State) -> Out_2
The way I've structured the code, the callbacks that folks here would like to have as separate functions are separate functions (e.g. output_given_a), and I've included as a comment above them what the corresponding desired @app.callback(...) call would be if multiple callbacks could target the same output. The router-callbacks immediately below the pairs of functions actually implements the logic. The bottom router implements the priority of input C.
One downside of this pattern is that the functions don't have their associated callback information immediately above them in the source file, but the corresponding upside is that all the information one needs to understand what functions could be involved in updating a given input is centralized within the actual router callbacks.