0
# Framework Extensions
1
2
Specialized components and functions for integrating interactive tables into various Python application frameworks. Each extension provides framework-specific functionality while maintaining the core ITables API and configuration system.
3
4
## Capabilities
5
6
### Streamlit Integration
7
8
Interactive table component for Streamlit applications, providing seamless integration with Streamlit's component system and reactivity model.
9
10
```python { .api }
11
def interactive_table(df, key=None, caption=None, **kwargs):
12
"""
13
Render DataFrame as interactive datatable in Streamlit applications.
14
15
Parameters:
16
- df: Pandas/Polars DataFrame or Series to display
17
- key (str, optional): Unique key for Streamlit component (for caching/reactivity)
18
- caption (str, optional): Table caption text
19
- **kwargs: ITableOptions - Configuration options
20
21
Returns:
22
CustomComponent: Streamlit component instance
23
"""
24
```
25
26
### Shiny Integration
27
28
Functions for rendering interactive tables in Shiny for Python applications, with support for row selection events and reactive programming patterns.
29
30
```python { .api }
31
def init_itables(connected=False, dt_bundle=None):
32
"""
33
Initialize DataTables library for Shiny applications.
34
35
Parameters:
36
- connected (bool): If True, load from CDN; if False, use offline bundle
37
- dt_bundle (str | Path, optional): Custom DataTables bundle path
38
39
Returns:
40
str: HTML content to include in Shiny app header
41
"""
42
43
def DT(df, caption=None, **kwargs):
44
"""
45
Render DataFrame as interactive table in Shiny applications with row selection.
46
47
Parameters:
48
- df: Pandas/Polars DataFrame or Series to display
49
- caption (str, optional): Table caption text
50
- **kwargs: ITableOptions - Configuration options
51
52
Returns:
53
str: HTML representation with Shiny integration
54
55
Note: If table_id is provided, selected rows are available as Shiny input
56
"""
57
```
58
59
### Dash Integration
60
61
Dash component class for creating interactive tables in Dash applications, with full integration into Dash's callback system and property updates.
62
63
```python { .api }
64
class ITable:
65
"""
66
Dash component for interactive tables.
67
68
Properties:
69
- id (str): Unique component identifier (required)
70
- All ITableOptions as component properties
71
- selected_rows (list): Currently selected row indices (output property)
72
"""
73
74
def __init__(self, id, df=None, caption=None, **kwargs):
75
"""
76
Initialize ITable Dash component.
77
78
Parameters:
79
- id (str): Unique component ID (required, must be non-empty string)
80
- df: Pandas/Polars DataFrame or Series to display
81
- caption (str, optional): Table caption text
82
- **kwargs: ITableOptions - Configuration options
83
84
Raises:
85
ValueError: If id is not a non-empty string
86
"""
87
88
# Additional Dash utilities
89
ITABLE_PROPERTIES: dict # Component property definitions
90
ITableOutputs: type # Output property types for callbacks
91
def updated_itable_outputs(*args): # Helper for handling updated outputs
92
```
93
94
### Jupyter Widget Integration
95
96
AnyWidget-based interactive table widget for Jupyter environments, providing reactive properties and bi-directional communication between Python and JavaScript.
97
98
```python { .api }
99
class ITable:
100
"""
101
AnyWidget-based interactive table widget.
102
103
Traits (automatically synced with frontend):
104
- caption (str): Table caption
105
- classes (str): CSS classes
106
- selected_rows (list[int]): Selected row indices
107
- style (str): CSS styles (private, use style property)
108
"""
109
110
def __init__(self, df=None, caption=None, **kwargs):
111
"""
112
Initialize ITable widget.
113
114
Parameters:
115
- df: Pandas/Polars DataFrame or Series to display
116
- caption (str, optional): Table caption text
117
- **kwargs: ITableOptions - Configuration options
118
"""
119
120
def update(self, df=None, caption=None, **kwargs):
121
"""
122
Update table data, attributes, or DataTable arguments.
123
124
Parameters:
125
- df: New DataFrame/Series (None = keep current)
126
- caption (str, optional): New caption (None = keep current)
127
- **kwargs: Updated configuration options (None values remove options)
128
129
Returns:
130
None (updates widget in-place)
131
"""
132
133
@property
134
def df(self):
135
"""Get current DataFrame."""
136
137
@df.setter
138
def df(self, df):
139
"""Set new DataFrame (triggers update)."""
140
141
@property
142
def style(self):
143
"""Get current CSS styles."""
144
145
@style.setter
146
def style(self, style):
147
"""Set CSS styles."""
148
```
149
150
## Usage Examples
151
152
### Streamlit Application
153
154
```python
155
import streamlit as st
156
import pandas as pd
157
from itables.streamlit import interactive_table
158
159
# Create sample data
160
df = pd.DataFrame({
161
'Name': ['Alice', 'Bob', 'Charlie'],
162
'Score': [95, 87, 92],
163
'Grade': ['A', 'B', 'A']
164
})
165
166
# Display in Streamlit
167
st.title("Student Scores")
168
interactive_table(df,
169
key="student_table",
170
caption="Class Scores",
171
pageLength=10,
172
column_filters="header")
173
174
# Use with Streamlit columns
175
col1, col2 = st.columns(2)
176
with col1:
177
interactive_table(df.head(2), key="table1")
178
with col2:
179
interactive_table(df.tail(2), key="table2")
180
```
181
182
### Shiny Application
183
184
```python
185
from shiny import App, ui, render
186
import pandas as pd
187
from itables.shiny import DT, init_itables
188
189
# Sample data
190
df = pd.DataFrame({
191
'Product': ['A', 'B', 'C', 'D'],
192
'Sales': [100, 250, 300, 150]
193
})
194
195
app_ui = ui.page_fluid(
196
ui.HTML(init_itables(connected=False)), # Initialize ITables
197
ui.h2("Sales Dashboard"),
198
ui.output_ui("table"),
199
ui.output_text("selection")
200
)
201
202
def server(input, output, session):
203
@output
204
@render.ui
205
def table():
206
return ui.HTML(DT(df,
207
table_id="sales_table",
208
pageLength=5,
209
select=True))
210
211
@output
212
@render.text
213
def selection():
214
selected = input.sales_table_selected_rows()
215
if selected:
216
return f"Selected rows: {selected}"
217
return "No rows selected"
218
219
app = App(app_ui, server)
220
```
221
222
### Dash Application
223
224
```python
225
import dash
226
from dash import html, dcc, callback, Input, Output
227
import pandas as pd
228
from itables.dash import ITable
229
230
# Sample data
231
df = pd.DataFrame({
232
'City': ['New York', 'London', 'Tokyo', 'Paris'],
233
'Population': [8.4, 8.9, 13.9, 2.1],
234
'Country': ['USA', 'UK', 'Japan', 'France']
235
})
236
237
app = dash.Dash(__name__)
238
239
app.layout = html.Div([
240
html.H1("City Population Data"),
241
ITable(
242
id="city-table",
243
df=df,
244
caption="World Cities",
245
pageLength=10,
246
column_filters="header",
247
select={'style': 'multi'}
248
),
249
html.Div(id="selection-output")
250
])
251
252
@callback(
253
Output("selection-output", "children"),
254
Input("city-table", "selected_rows")
255
)
256
def update_selection(selected_rows):
257
if selected_rows:
258
selected_cities = df.iloc[selected_rows]['City'].tolist()
259
return f"Selected cities: {', '.join(selected_cities)}"
260
return "No cities selected"
261
262
if __name__ == "__main__":
263
app.run_server(debug=True)
264
```
265
266
### Jupyter Widget
267
268
```python
269
import pandas as pd
270
from itables.widget import ITable
271
272
# Create widget with initial data
273
df = pd.DataFrame({
274
'Item': ['Widget A', 'Widget B', 'Widget C'],
275
'Price': [10.50, 15.25, 8.75],
276
'Stock': [100, 50, 200]
277
})
278
279
# Create interactive widget
280
table_widget = ITable(df,
281
caption="Inventory",
282
pageLength=5,
283
column_filters="header")
284
285
# Display widget
286
table_widget
287
288
# Update data dynamically
289
new_df = pd.DataFrame({
290
'Item': ['Widget D', 'Widget E'],
291
'Price': [12.00, 9.50],
292
'Stock': [75, 150]
293
})
294
295
table_widget.update(df=new_df, caption="Updated Inventory")
296
297
# Access selected rows
298
print(f"Selected rows: {table_widget.selected_rows}")
299
300
# Modify styling
301
table_widget.style = "background-color: #f0f0f0; border: 1px solid #ccc;"
302
table_widget.classes = "display compact hover"
303
```
304
305
### Widget Event Handling
306
307
```python
308
from ipywidgets import Output
309
import pandas as pd
310
from itables.widget import ITable
311
312
# Create output widget for logging
313
output = Output()
314
display(output)
315
316
# Create table widget
317
df = pd.DataFrame({'A': [1, 2, 3], 'B': ['x', 'y', 'z']})
318
table = ITable(df, select={'style': 'multi'})
319
320
# Monitor selection changes
321
def on_selection_change(change):
322
with output:
323
print(f"Selection changed: {change['new']}")
324
325
table.observe(on_selection_change, names='selected_rows')
326
table
327
```
328
329
## Framework-Specific Features
330
331
### Streamlit Features
332
- Automatic integration with Streamlit's component system
333
- Unique key parameter for proper caching and reactivity
334
- Compatible with Streamlit's column layouts and containers
335
336
### Shiny Features
337
- Row selection events accessible as Shiny inputs
338
- Integration with Shiny's reactive programming model
339
- Support for both connected and offline DataTables modes
340
- Automatic input value updates via JavaScript integration
341
342
### Dash Features
343
- Full Dash component with standard property system
344
- Integration with Dash callbacks for reactivity
345
- Selected rows available as output property
346
- Support for all standard Dash component patterns
347
348
### Jupyter Widget Features
349
- Bi-directional data synchronization
350
- Reactive properties using traitlets
351
- Widget composition and event handling
352
- Integration with ipywidgets ecosystem