Show and Tell: Dictionary Based Callback Decorator

This is an enhancement for the developer.
Due to the some of the restrictions on callback graphs, you may find yourself writing more complex callbacks with lots of Input, Output and State dependencies. I have written a dict_callback decorator. The parameters are pretty much the same as the @callback decorator. The difference is that the callback function is presented with the inputs and states as a dictionary rather than an array and the output is provided as a dictionary. Here’s a usage example taken from the most basic example in the documentation

@app.dict_callback(
    Output(component_id='my-output', component_property='children'),
    Input(component_id='my-input', component_property='value')
)
def update_output_div(inputs, states):
    input_value = inputs['my-input.value']
    return {'my-output.children': 'Output: {}'.format(input_value)}

While it seems like a lot more work for this simple example, when you have lots of Inputs, States and/or Outputs. It is very convenient since you don’t have to remember where in the input array something is. For example, if you add an additional Input, you don’t have to worry about all your states shifted over since you now access inputs or states by dictionary keys rather than by number. I believe this is a more pythonic way to code.

Originally, I wrote this before the pattern matching feature came out, so I had to adapt this to accommodate dictionaries as component tags. If there is interest, I can show how you can use this mechanism as well.

Enough said. Currently, the code sits in a dict-callback-decorator branch of our fork of the dash repository at
https://github.com/WestHealth/dash/tree/dict-callback-decorator. If there is interest, I can give more examples of it’s usage

Eventually, I hope to submit this as a pull request to the main fork of dahs

1 Like

Thank you for this development, @hlu-whi .
I have less experience with forked repositories. Can you please share with me how I would use the dict-callback-decorator. Do i need to pip install a library?

@adamschroeder
Since the intent of this is to propose it as an addition to dash, it wouldn’t make sense to incorporate it into pypi where you could pip install it. However, you can use it by cloning the repository and using pip. I believe the following commands will work.
Find some place you want to clone then

git clone https://github.com/WestHealth/dash.git
cd dash
git branch dict-callback-decorator
pip install -e .

If you are installing in a virtual environment be sure to activate it. I recommend a virtual environment as this would conflict if you’ve already installed dash on your system. Since this is an addition of the regular dash functions should still work however, I’ve forked of the current dev branch not the latest release so it may have features not yet vetted for release.

Feel free to respond if you have questions or want more examples.

1 Like