0
# Special Values and Control
1
2
Dash provides special values and utilities for controlling callback execution, preventing component updates, and making partial modifications to data structures.
3
4
## Capabilities
5
6
### No Update
7
8
Prevent component updates in callback outputs.
9
10
```python { .api }
11
class NoUpdate:
12
"""Sentinel value to prevent component property updates in callbacks."""
13
pass
14
15
no_update: NoUpdate # Singleton instance, alias for NoUpdate()
16
```
17
18
### Prevent Update Exception
19
20
Stop callback execution and prevent any updates.
21
22
```python { .api }
23
class PreventUpdate(Exception):
24
"""
25
Exception to prevent callback execution and component updates.
26
27
Raise this exception in a callback to stop execution without
28
updating any outputs or triggering errors.
29
"""
30
pass
31
```
32
33
### Patch Operations
34
35
Perform partial updates on lists and dictionaries without replacing entire structures.
36
37
```python { .api }
38
class Patch:
39
"""
40
Enable partial updates to lists and dictionaries in callback outputs.
41
42
Instead of replacing entire data structures, Patch allows you to
43
modify specific elements, append items, or make targeted changes.
44
"""
45
46
def __init__(self): ...
47
48
def append(self, item: Any) -> 'Patch':
49
"""Append item to end of list."""
50
51
def prepend(self, item: Any) -> 'Patch':
52
"""Add item to beginning of list."""
53
54
def insert(self, index: int, item: Any) -> 'Patch':
55
"""Insert item at specific index in list."""
56
57
def remove(self, item: Any) -> 'Patch':
58
"""Remove first occurrence of item from list."""
59
60
def clear(self) -> 'Patch':
61
"""Remove all items from list or dictionary."""
62
63
def __setitem__(self, key: Union[int, str], value: Any):
64
"""Set item at key/index."""
65
66
def __delitem__(self, key: Union[int, str]):
67
"""Delete item at key/index."""
68
```
69
70
## Usage Examples
71
72
### Using NoUpdate
73
74
```python
75
from dash import Dash, html, dcc, callback, Input, Output, no_update
76
77
app = Dash(__name__)
78
79
app.layout = html.Div([
80
dcc.Input(id='input1', placeholder='Type here...'),
81
dcc.Input(id='input2', placeholder='Or here...'),
82
html.Div(id='output1'),
83
html.Div(id='output2')
84
])
85
86
@callback(
87
[Output('output1', 'children'),
88
Output('output2', 'children')],
89
[Input('input1', 'value'),
90
Input('input2', 'value')]
91
)
92
def update_outputs(input1, input2):
93
# Only update output1 if input1 has a value
94
if input1:
95
output1_value = f'Input 1: {input1}'
96
else:
97
output1_value = no_update
98
99
# Only update output2 if input2 has a value
100
if input2:
101
output2_value = f'Input 2: {input2}'
102
else:
103
output2_value = no_update
104
105
return output1_value, output2_value
106
```
107
108
### Using PreventUpdate
109
110
```python
111
from dash import Dash, html, dcc, callback, Input, Output, PreventUpdate
112
113
app = Dash(__name__)
114
115
app.layout = html.Div([
116
dcc.Input(id='password', type='password', placeholder='Enter password'),
117
html.Div(id='secure-content')
118
])
119
120
@callback(
121
Output('secure-content', 'children'),
122
Input('password', 'value')
123
)
124
def show_secure_content(password):
125
if not password:
126
# Don't update anything if no password entered
127
raise PreventUpdate
128
129
if password != 'secret123':
130
return html.Div('Incorrect password', style={'color': 'red'})
131
132
return html.Div([
133
html.H2('Secure Content'),
134
html.P('This is confidential information.')
135
])
136
```
137
138
### Using Patch for List Operations
139
140
```python
141
from dash import Dash, html, dcc, callback, Input, Output, State, Patch
142
143
app = Dash(__name__)
144
145
app.layout = html.Div([
146
dcc.Store(id='list-store', data=['Item 1', 'Item 2']),
147
dcc.Input(id='new-item', placeholder='Add new item'),
148
html.Button('Add', id='add-btn'),
149
html.Button('Clear All', id='clear-btn'),
150
html.Div(id='item-list')
151
])
152
153
@callback(
154
Output('list-store', 'data'),
155
[Input('add-btn', 'n_clicks'),
156
Input('clear-btn', 'n_clicks')],
157
[State('new-item', 'value'),
158
State('list-store', 'data')],
159
prevent_initial_call=True
160
)
161
def update_list(add_clicks, clear_clicks, new_item, current_list):
162
from dash import callback_context
163
164
if not callback_context.triggered:
165
raise PreventUpdate
166
167
trigger = callback_context.triggered[0]['prop_id']
168
patched_list = Patch()
169
170
if 'add-btn' in trigger and new_item:
171
patched_list.append(new_item)
172
return patched_list
173
174
elif 'clear-btn' in trigger:
175
patched_list.clear()
176
return patched_list
177
178
raise PreventUpdate
179
180
@callback(
181
Output('item-list', 'children'),
182
Input('list-store', 'data')
183
)
184
def display_list(items):
185
if not items:
186
return html.P('No items in list')
187
188
return html.Ul([
189
html.Li(item) for item in items
190
])
191
```
192
193
### Using Patch for Dictionary Operations
194
195
```python
196
from dash import Dash, html, dcc, callback, Input, Output, State, Patch
197
198
app = Dash(__name__)
199
200
app.layout = html.Div([
201
dcc.Store(id='dict-store', data={'count': 0, 'name': 'App'}),
202
html.Button('Increment Count', id='increment-btn'),
203
dcc.Input(id='name-input', placeholder='Update name'),
204
html.Button('Update Name', id='name-btn'),
205
html.Div(id='dict-display')
206
])
207
208
@callback(
209
Output('dict-store', 'data'),
210
[Input('increment-btn', 'n_clicks'),
211
Input('name-btn', 'n_clicks')],
212
[State('name-input', 'value'),
213
State('dict-store', 'data')],
214
prevent_initial_call=True
215
)
216
def update_dict(increment_clicks, name_clicks, new_name, current_dict):
217
from dash import callback_context
218
219
if not callback_context.triggered:
220
raise PreventUpdate
221
222
trigger = callback_context.triggered[0]['prop_id']
223
patched_dict = Patch()
224
225
if 'increment-btn' in trigger:
226
patched_dict['count'] = current_dict['count'] + 1
227
return patched_dict
228
229
elif 'name-btn' in trigger and new_name:
230
patched_dict['name'] = new_name
231
return patched_dict
232
233
raise PreventUpdate
234
235
@callback(
236
Output('dict-display', 'children'),
237
Input('dict-store', 'data')
238
)
239
def display_dict(data):
240
return html.Div([
241
html.P(f"Name: {data.get('name', 'Unknown')}"),
242
html.P(f"Count: {data.get('count', 0)}")
243
])
244
```
245
246
### Conditional Updates with Multiple Outputs
247
248
```python
249
@callback(
250
[Output('output1', 'children'),
251
Output('output2', 'style'),
252
Output('output3', 'className')],
253
Input('trigger', 'value')
254
)
255
def conditional_updates(value):
256
# Update all outputs
257
if value == 'update_all':
258
return 'Updated!', {'color': 'green'}, 'success'
259
260
# Update only first output
261
elif value == 'update_first':
262
return 'First updated!', no_update, no_update
263
264
# Update only styling
265
elif value == 'update_style':
266
return no_update, {'color': 'blue'}, 'info'
267
268
# No updates
269
else:
270
raise PreventUpdate
271
```
272
273
## Types
274
275
```python { .api }
276
NoUpdate = Any # Sentinel type for preventing updates
277
PreventUpdate = Exception # Exception type for preventing callback execution
278
Patch = Any # Partial update utility type
279
```