0
# Callback System
1
2
The callback system is the heart of Dash's reactive programming model, enabling automatic updates of components based on user interactions. Callbacks define relationships between component properties through Input, Output, and State dependencies.
3
4
## Capabilities
5
6
### Dependency Classes
7
8
Define relationships between components for reactive updates.
9
10
```python { .api }
11
class Input:
12
def __init__(self, component_id: ComponentIdType, component_property: str):
13
"""
14
Define input dependency that triggers callback execution.
15
16
Parameters:
17
- component_id: ID of the component to watch
18
- component_property: Property of the component to watch
19
"""
20
21
class Output:
22
def __init__(self, component_id: ComponentIdType, component_property: str):
23
"""
24
Define output dependency that gets updated by callback.
25
26
Parameters:
27
- component_id: ID of the component to update
28
- component_property: Property of the component to update
29
"""
30
31
class State:
32
def __init__(self, component_id: ComponentIdType, component_property: str):
33
"""
34
Define state dependency that provides values without triggering.
35
36
Parameters:
37
- component_id: ID of the component to read
38
- component_property: Property of the component to read
39
"""
40
```
41
42
### Callback Registration
43
44
Register reactive functions that respond to component interactions.
45
46
```python { .api }
47
def callback(
48
output: Union[Output, List[Output]],
49
inputs: Union[Input, List[Input]] = None,
50
state: Union[State, List[State]] = None,
51
prevent_initial_call: bool = None,
52
prevent_initial_callbacks: bool = None,
53
background: bool = None,
54
manager: Any = None,
55
running: List[Tuple[Output, Any]] = None,
56
progress: List[Output] = None,
57
progress_default: List[Any] = None,
58
cancel: List[Input] = None,
59
cache_by: List[Union[Input, State]] = None,
60
long_callback_manager: Any = None
61
) -> Callable:
62
"""
63
Decorator for registering callback functions.
64
65
Parameters:
66
- output: Output dependencies (what gets updated)
67
- inputs: Input dependencies (what triggers the callback)
68
- state: State dependencies (additional values)
69
- prevent_initial_call: Skip callback on initial load
70
- background: Execute in background thread
71
- manager: Background callback manager
72
- running: Components to update while callback runs
73
- progress: Components for progress reporting
74
- cancel: Inputs that can cancel background callbacks
75
"""
76
77
def clientside_callback(
78
clientside_function: Union[ClientsideFunction, str],
79
output: Union[Output, List[Output]],
80
inputs: Union[Input, List[Input]] = None,
81
state: Union[State, List[State]] = None,
82
prevent_initial_call: bool = None
83
):
84
"""
85
Register JavaScript callback for client-side execution.
86
87
Parameters:
88
- clientside_function: JavaScript function or ClientsideFunction
89
- output: Output dependencies
90
- inputs: Input dependencies
91
- state: State dependencies
92
"""
93
```
94
95
### Clientside Functions
96
97
Execute callbacks in the browser using JavaScript for improved performance.
98
99
```python { .api }
100
class ClientsideFunction:
101
def __init__(self, namespace: str, function_name: str):
102
"""
103
Reference to JavaScript function for clientside callbacks.
104
105
Parameters:
106
- namespace: JavaScript namespace containing the function
107
- function_name: Name of the JavaScript function
108
"""
109
```
110
111
### Pattern-Matching Callbacks
112
113
Use wildcards to create callbacks that respond to dynamic component patterns.
114
115
```python { .api }
116
MATCH: Any = _Wildcard("MATCH") # Match any component ID
117
ALL: Any = _Wildcard("ALL") # Match all component IDs
118
ALLSMALLER: Any = _Wildcard("ALLSMALLER") # Match all smaller indices
119
120
# Usage in component IDs
121
{"type": "button", "index": MATCH} # Match any button
122
{"type": "button", "index": ALL} # Match all buttons
123
{"type": "button", "index": ALLSMALLER} # Match buttons with smaller indices
124
```
125
126
### Callback Context
127
128
Access information about callback execution and trigger events.
129
130
```python { .api }
131
callback_context: CallbackContext # Global callback context
132
ctx: CallbackContext # Alias for callback_context
133
134
class CallbackContext:
135
@property
136
def triggered(self) -> List[Dict[str, Any]]:
137
"""List of triggered inputs with their values."""
138
139
@property
140
def inputs(self) -> Dict[str, Any]:
141
"""Dictionary of all input values."""
142
143
@property
144
def states(self) -> Dict[str, Any]:
145
"""Dictionary of all state values."""
146
147
@property
148
def outputs_list(self) -> List[Dict[str, Any]]:
149
"""List of output specifications."""
150
151
@property
152
def inputs_list(self) -> List[Dict[str, Any]]:
153
"""List of input specifications."""
154
155
@property
156
def states_list(self) -> List[Dict[str, Any]]:
157
"""List of state specifications."""
158
159
@property
160
def response(self) -> Dict[str, Any]:
161
"""Response information for the callback."""
162
```
163
164
### Property Updates
165
166
Programmatically update component properties outside of callbacks.
167
168
```python { .api }
169
def set_props(component_id: str, props: Dict[str, Any]):
170
"""
171
Update component properties programmatically.
172
173
Parameters:
174
- component_id: ID of component to update
175
- props: Dictionary of properties to update
176
"""
177
```
178
179
## Usage Examples
180
181
### Basic Callback
182
183
```python
184
from dash import Dash, html, dcc, callback, Input, Output
185
186
app = Dash(__name__)
187
188
app.layout = html.Div([
189
dcc.Input(id='input', value='Initial'),
190
html.Div(id='output')
191
])
192
193
@callback(
194
Output('output', 'children'),
195
Input('input', 'value')
196
)
197
def update_output(value):
198
return f'You entered: {value}'
199
```
200
201
### Multiple Inputs and Outputs
202
203
```python
204
@callback(
205
[Output('output1', 'children'), Output('output2', 'children')],
206
[Input('input1', 'value'), Input('input2', 'value')],
207
State('state-input', 'value')
208
)
209
def update_multiple(input1, input2, state_value):
210
return f'Input 1: {input1}', f'Input 2: {input2}, State: {state_value}'
211
```
212
213
### Pattern-Matching Callback
214
215
```python
216
@callback(
217
Output({'type': 'output', 'index': MATCH}, 'children'),
218
Input({'type': 'button', 'index': MATCH}, 'n_clicks'),
219
prevent_initial_call=True
220
)
221
def update_matched_output(n_clicks):
222
return f'Button clicked {n_clicks} times'
223
```
224
225
### Clientside Callback
226
227
```python
228
from dash import clientside_callback, ClientsideFunction
229
230
# JavaScript function in assets/custom.js:
231
# window.dash_clientside = Object.assign({}, window.dash_clientside, {
232
# clientside: {
233
# large_params_function: function(value) {
234
# return 'Client says: ' + value;
235
# }
236
# }
237
# });
238
239
clientside_callback(
240
ClientsideFunction(namespace='clientside', function_name='large_params_function'),
241
Output('output', 'children'),
242
Input('input', 'value')
243
)
244
```
245
246
### Using Callback Context
247
248
```python
249
from dash import callback_context
250
251
@callback(
252
Output('output', 'children'),
253
[Input('btn1', 'n_clicks'), Input('btn2', 'n_clicks')]
254
)
255
def update_output(btn1, btn2):
256
if not callback_context.triggered:
257
return "No button clicked yet"
258
259
button_id = callback_context.triggered[0]['prop_id'].split('.')[0]
260
return f'Button {button_id} was clicked'
261
```
262
263
### Background Callback
264
265
```python
266
from dash.long_callback import DiskcacheManager
267
import diskcache
268
269
cache = diskcache.Cache("./cache")
270
background_callback_manager = DiskcacheManager(cache)
271
272
@callback(
273
Output('output', 'children'),
274
Input('button', 'n_clicks'),
275
background=True,
276
manager=background_callback_manager,
277
running=[
278
(Output('loading', 'children'), 'Loading...'),
279
(Output('button', 'disabled'), True)
280
],
281
progress=[Output('progress', 'value'), Output('progress', 'max')],
282
progress_default=[0, 100]
283
)
284
def long_running_callback(set_progress, n_clicks):
285
import time
286
for i in range(100):
287
time.sleep(0.1)
288
set_progress((i, 100))
289
return f'Completed after {n_clicks} clicks'
290
```
291
292
## Types
293
294
```python { .api }
295
ComponentIdType = Union[str, Dict, Component]
296
DependencyType = Union[Input, Output, State]
297
DependencyList = List[DependencyType]
298
CallbackFunction = Callable[..., Any]
299
CallbackReturnType = Union[Any, List[Any], Dict[str, Any]]
300
CallbackContext = Any
301
ClientsideFunction = Any
302
BackgroundCallbackManager = Any
303
```