Handel multiple callback outputs programmatically

According to Dash’s user guide, each Dash callback function can only update a single Output property. I have multiple outputs to be updated for a callback input. It is advised to define a callback function for each output. However, it is very tedious when the outputs to be updated are many and very similar. Is there anyway to define a callback function programmatically to handle multiple outputs?

3 Likes

Good question. There are a few patterns in Python that can help out with this.

1 - Functions can return other functions
2 - Decorators can be called directly.

I highly reccommend this essay on Stack Overflow about decorators: https://stackoverflow.com/questions/739654/how-to-make-a-chain-of-function-decorators/1594484#1594484

In practice, this might look something like:

output_elements = ['id1', 'id2']

def create_callback(output):
     def callback(input_value):
        if output == 'id1':
            # do something
        elif output == 'id2':
            # do something different
    return callback

for output_element in output_elements:
     dynamically_generated_function = create_callback(output_element)
    app.callback(Output(output_element, '...'), [Input(...)])(dynamically_generated_function)
9 Likes

Awesome! I just tried your advice, it worked!

1 Like

Great! Here’s another real-world example of generating dash callback functions: https://github.com/plotly/dash/issues/59#issuecomment-313214212

In my case, this does not seem to work.

Also see this topic here: Dynamic Controls and Dynamic Output Components.