✊🏿 Black Lives Matter. Please consider donating to Black Girls Code today.
🐇 Announcing Dash VTK for 3d simulation graphics. Check out the March webinar.

Using value from callback as a variable in non dash python code

I am trying to find examples of this but can’t seem to, so I apologize if this is an easy answer

Basically i want to use whatever I get from the callback later in the python code to do analysis or other aggregations before i call dash again. So below, I would want to use my_variable in other parts of the python code, but python doesnt recognize the variable when testing, so I am wondering if this is possible

IE I want to use my_variable, which is the item selected in the dash dropdown, to use in a pandassql function or other python function

I think I get how to use this in other dash components but not assigning to a variable I can use further down in python code

@app.callback(
    Output(component_id='output-graph', component_property='children'),
    [Input(component_id='your-dropdown-id', component_property='value')]
)

def update_output_div(input_value):
    my_variable = input_value
    return my_variable

Hey, this is a common problem users face when using dash. The way dash works is that your callback could be executed by one of many machines, which can’t necessarily share resources. This is to make it so apps can scale to have many users (more users than a single computer could handle for example). So that means whatever the callback needs to use has to be passed in via the callback inputs or state variables (which ultimately come from the browser). To have some data persist between callbacks, it needs to be stored in a user’s browser. For this you can use a dash_core_components.Store component. For example

app.layout=html.Div(id='main',children=[
    ...
    html.Button(id='do-first-computation'),
    dcc.Store(id='result-of-first-computation'),
    html.Button(id='use-result'),
   ...
])

@app.callback(
    Output('result-of-first-computation','data'),
    [Input('do-first-computation','n_clicks'), ...  (other inputs) ...])
def first_computation(button_n_clicks,....):
    .... compute result  ...
    return result % result gets stored in the Store
)

@app.callback(
    ... some output ...
   [Input('use-result','n_clicks'), ... (other inputs) ...],
   [State('result-of-first-computation','data')])
def use_result(use_result_button_n_clicks,...,result_of_first_computation,...):
     .... use the result ....
1 Like

this helps…thanks for pointing this out