0
# Type System
1
2
Comprehensive type definitions for configuration options, JavaScript integration, and DataFrame compatibility across Pandas and Polars. The type system ensures type safety, provides clear API contracts, and enables proper IDE support and documentation.
3
4
## Capabilities
5
6
### Core Type Aliases
7
8
Fundamental type definitions for data compatibility and JavaScript integration, providing a common interface across different DataFrame libraries.
9
10
```python { .api }
11
# Data compatibility
12
DataFrameOrSeries = Any
13
"""
14
Type alias for supported data types:
15
- pandas.DataFrame, pandas.Series
16
- polars.DataFrame, polars.Series
17
- numpy.ndarray, numpy.generic
18
- pandas.Styler (styled DataFrames)
19
"""
20
21
# JavaScript integration
22
class JavascriptFunction(str):
23
"""
24
String subclass for JavaScript function code that will be evaluated.
25
Functions must start with 'function(' pattern.
26
27
Usage: JavascriptFunction("function(data) { return data.length; }")
28
29
Security Warning: Only use with trusted code.
30
"""
31
32
class JavascriptCode(str):
33
"""
34
String subclass for JavaScript code snippets that will be evaluated.
35
36
Usage: JavascriptCode("console.log('Hello from ITables');")
37
38
Security Warning: Only use with trusted code.
39
"""
40
```
41
42
### Configuration Type Definitions
43
44
Structured type definitions for all configuration options, providing complete specification of available parameters and their expected types.
45
46
```python { .api }
47
class ITableOptions(TypedDict):
48
"""
49
Configuration options for show() function and ITable components.
50
All options are optional (NotRequired).
51
"""
52
53
# Display and styling
54
classes: str | list[str] # CSS classes for table styling
55
style: str | dict[str, str] # CSS styles for table appearance
56
selected_rows: list[int] # Pre-selected row indices
57
58
# Index and data control
59
showIndex: bool | str # Index display control ("auto", True, False)
60
maxBytes: int | str # Maximum data size before downsampling
61
maxRows: int # Maximum rows before downsampling
62
maxColumns: int # Maximum columns before downsampling
63
64
# Content handling
65
allow_html: bool # Allow HTML content in table cells
66
table_id: str # Custom HTML table ID
67
68
# DataTables library configuration
69
dt_url: str # DataTables JavaScript bundle URL
70
dt_bundle: str | Path # Local DataTables bundle path
71
connected: bool # Load from CDN vs offline bundle
72
display_logo_when_loading: bool # Show ITables logo while loading
73
74
# Table features
75
footer: bool # Show table footer
76
column_filters: str | bool # Column filtering UI ("header", "footer", False)
77
text_in_header_can_be_selected: bool # Header text selectability
78
79
# Behavior and warnings
80
warn_on_unexpected_types: bool # Warn about unexpected data types
81
warn_on_selected_rows_not_rendered: bool # Warn about selection issues
82
warn_on_undocumented_option: bool # Warn about unknown options
83
warn_on_unexpected_option_type: bool # Warn about type mismatches
84
85
# Advanced rendering
86
use_to_html: bool # Use DataFrame.to_html() instead of JSON serialization
87
88
class DTForITablesOptions(TypedDict):
89
"""
90
Options passed to DataTable constructor in framework extensions.
91
Subset of ITableOptions with additional internal parameters.
92
"""
93
94
# Table content and structure
95
caption: str # Table caption text
96
classes: str | list[str] # CSS classes
97
style: str | dict[str, str] # CSS styles
98
data_json: str # JSON-serialized table data
99
table_html: str # Pre-rendered HTML table structure
100
table_style: str # CSS styles for styled DataFrames
101
102
# Selection and interaction
103
selected_rows: list[int] # Selected row indices
104
filtered_row_count: int # Number of rows filtered by downsampling
105
106
# Status and messaging
107
downsampling_warning: str # Warning message for downsampled data
108
text_in_header_can_be_selected: bool # Header text selectability
109
column_filters: str | bool # Column filtering configuration
110
keys_to_be_evaluated: list[list[int | str]] # JavaScript evaluation keys
111
112
# Internal options (used in templates, not passed to DataTables)
113
connected: bool # Library loading mode
114
dt_url: str # DataTables bundle URL
115
display_logo_when_loading: bool # Loading logo display
116
117
class DataTableOptions(TypedDict):
118
"""
119
Native DataTables.net configuration options.
120
See https://datatables.net/reference/option/ for complete documentation.
121
"""
122
123
# Pagination and display
124
lengthMenu: list | list[list] # Page length options
125
pageLength: int # Default page length
126
127
# Sorting and ordering
128
order: list[list] | dict # Default sort configuration
129
ordering: bool | dict[str, bool] # Enable/disable sorting
130
131
# Layout and positioning
132
layout: dict[str, str | dict | None] # Control positioning
133
134
# Column configuration
135
columnDefs: list[dict] # Column-specific settings
136
137
# Appearance and behavior
138
autoWidth: bool # Automatic column width calculation
139
scrollX: bool # Horizontal scrolling
140
scrollY: str # Vertical scrolling height
141
scrollCollapse: bool # Collapse scrolling container
142
paging: bool # Enable pagination
143
144
# Localization
145
language: dict[str, str] # UI text customization
146
147
# Search functionality
148
search: dict # Global search configuration
149
searchCols: list # Column-specific search
150
151
# State management
152
stateSave: bool # Save table state
153
stateDuration: int # State persistence duration
154
155
# Callbacks (JavaScript functions)
156
initComplete: JavascriptFunction # Initialization complete callback
157
fnInfoCallback: JavascriptFunction # Info display callback
158
drawCallback: JavascriptFunction # Table draw callback
159
160
# Extensions
161
buttons: list[str | dict] # Export/action buttons
162
columnControl: Any # Column visibility control
163
fixedColumns: dict[str, int] # Fixed column configuration
164
searchPanes: dict # Search panes extension
165
searchBuilder: dict # Search builder extension
166
rowGroup: dict # Row grouping extension
167
select: bool | str | dict # Row selection configuration
168
keys: bool # Keyboard navigation
169
```
170
171
### Validation and Type Checking
172
173
Functions for runtime validation and type checking of configuration options, providing development-time feedback and ensuring configuration correctness.
174
175
```python { .api }
176
def check_itable_arguments(kwargs, typed_dict):
177
"""
178
Validate arguments against TypedDict specification.
179
180
Parameters:
181
- kwargs (dict): Arguments to validate
182
- typed_dict (type): TypedDict class for validation
183
184
Returns:
185
None (raises exceptions or emits warnings for invalid arguments)
186
"""
187
188
def is_typeguard_available():
189
"""
190
Check if typeguard package is available for advanced type checking.
191
192
Returns:
193
bool: True if typeguard >= 4.4.1 is available, False otherwise
194
"""
195
196
def check_itable_argument_names(names, typed_dict):
197
"""
198
Validate that argument names are documented in TypedDict.
199
200
Parameters:
201
- names (set[str]): Argument names to check
202
- typed_dict (type): TypedDict class for validation
203
204
Returns:
205
None (emits warnings for undocumented arguments)
206
"""
207
208
def check_itable_argument_types(kwargs, typed_dict):
209
"""
210
Validate argument types against TypedDict specification.
211
Requires typeguard package.
212
213
Parameters:
214
- kwargs (dict): Arguments with values to type-check
215
- typed_dict (type): TypedDict class for validation
216
217
Returns:
218
None (emits warnings for type mismatches)
219
"""
220
```
221
222
## Usage Examples
223
224
### Basic Type Usage
225
226
```python
227
from itables import show
228
from itables.typing import DataFrameOrSeries, ITableOptions
229
import pandas as pd
230
231
# Type-annotated function
232
def display_data(df: DataFrameOrSeries, options: ITableOptions) -> None:
233
show(df, **options)
234
235
# Usage with proper typing
236
df = pd.DataFrame({'A': [1, 2, 3], 'B': ['x', 'y', 'z']})
237
config: ITableOptions = {
238
'pageLength': 10,
239
'classes': 'display compact',
240
'column_filters': 'header'
241
}
242
243
display_data(df, config)
244
```
245
246
### JavaScript Integration
247
248
```python
249
from itables.typing import JavascriptFunction, JavascriptCode
250
from itables import show
251
252
# Custom JavaScript function for formatting
253
format_function = JavascriptFunction("""
254
function(data, type, row) {
255
if (type === 'display' && data > 100) {
256
return '<span style="color: red;">' + data + '</span>';
257
}
258
return data;
259
}
260
""")
261
262
# Custom initialization code
263
init_code = JavascriptCode("""
264
console.log('Table initialized with custom styling');
265
$('#myTable').addClass('custom-highlight');
266
""")
267
268
# Use in table configuration
269
show(df,
270
columnDefs=[{
271
'targets': [1], # Target second column
272
'render': format_function
273
}],
274
initComplete=JavascriptFunction("""
275
function(settings, json) {
276
console.log('Table ready with', json.recordsTotal, 'records');
277
}
278
"""))
279
```
280
281
### Type Validation
282
283
```python
284
from itables.typing import check_itable_arguments, ITableOptions
285
import itables.options as opts
286
287
# Enable validation warnings
288
opts.warn_on_undocumented_option = True
289
opts.warn_on_unexpected_option_type = True
290
291
# This will trigger validation warnings
292
invalid_config = {
293
'pageLength': '10', # Should be int, not str
294
'unknown_option': True, # Not documented in ITableOptions
295
'classes': 123 # Should be str or list[str], not int
296
}
297
298
# Validation occurs automatically in show()
299
show(df, **invalid_config) # Emits warnings
300
```
301
302
### Advanced Configuration Types
303
304
```python
305
from typing import TypedDict
306
from itables.typing import ITableOptions, JavascriptFunction
307
308
# Custom configuration with type safety
309
class CustomTableConfig(TypedDict):
310
basic_options: ITableOptions
311
advanced_features: dict[str, any]
312
313
# DataTables extension configuration
314
search_builder_config = {
315
'searchBuilder': {
316
'columns': [0, 1, 2],
317
'conditions': {
318
'string': ['=', '!=', 'starts', 'contains'],
319
'number': ['=', '!=', '<', '>', 'between']
320
}
321
}
322
}
323
324
# Export buttons configuration
325
export_config = {
326
'buttons': [
327
'copy',
328
{
329
'extend': 'csv',
330
'text': 'Export CSV',
331
'filename': 'data_export'
332
},
333
{
334
'extend': 'excel',
335
'text': 'Export Excel'
336
}
337
]
338
}
339
340
show(df, **search_builder_config, **export_config)
341
```
342
343
### Framework-Specific Types
344
345
```python
346
# Dash component with proper typing
347
from itables.dash import ITable, ITableOutputs
348
from dash import callback, Input, Output
349
350
@callback(
351
Output('output-div', 'children'),
352
Input('my-table', 'selected_rows')
353
)
354
def update_output(selected_rows: list[int]) -> str:
355
if selected_rows:
356
return f"Selected {len(selected_rows)} rows"
357
return "No selection"
358
359
# Widget with type annotations
360
from itables.widget import ITable as WidgetITable
361
362
def create_widget(df: DataFrameOrSeries) -> WidgetITable:
363
return WidgetITable(
364
df=df,
365
pageLength=20,
366
select={'style': 'multi'}
367
)
368
```
369
370
## Type Safety Best Practices
371
372
### Configuration Validation
373
374
```python
375
# Use type checking during development
376
from typing import TYPE_CHECKING
377
378
if TYPE_CHECKING:
379
from itables.typing import ITableOptions
380
381
def safe_show(df, **kwargs):
382
"""Type-safe wrapper for show() function."""
383
# Runtime validation
384
from itables.typing import check_itable_arguments, ITableOptions
385
check_itable_arguments(kwargs, ITableOptions)
386
387
# Display table
388
from itables import show
389
show(df, **kwargs)
390
```
391
392
### JavaScript Safety
393
394
```python
395
from itables.typing import JavascriptFunction
396
397
def create_safe_callback(code: str) -> JavascriptFunction:
398
"""Create JavaScript callback with basic validation."""
399
if not code.strip().startswith('function('):
400
raise ValueError("JavaScript function must start with 'function('")
401
402
return JavascriptFunction(code)
403
404
# Usage
405
callback = create_safe_callback("""
406
function(settings, json) {
407
console.log('Callback executed safely');
408
}
409
""")
410
```
411
412
### Extension Development
413
414
```python
415
from typing import Protocol
416
from itables.typing import DataFrameOrSeries, ITableOptions
417
418
class TableRenderer(Protocol):
419
"""Protocol for table rendering implementations."""
420
421
def render(self, df: DataFrameOrSeries, **kwargs: ITableOptions) -> str:
422
"""Render DataFrame as HTML table."""
423
...
424
425
class CustomRenderer:
426
"""Custom table renderer implementing the protocol."""
427
428
def render(self, df: DataFrameOrSeries, **kwargs: ITableOptions) -> str:
429
# Custom rendering logic
430
return f"<div>Custom table with {len(df)} rows</div>"
431
```