CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-itables

Python library that transforms Pandas and Polars DataFrames into interactive DataTables with sorting, pagination, and filtering capabilities.

Pending
Overview
Eval results
Files

type-system.mddocs/

Type System

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.

Capabilities

Core Type Aliases

Fundamental type definitions for data compatibility and JavaScript integration, providing a common interface across different DataFrame libraries.

# Data compatibility
DataFrameOrSeries = Any
"""
Type alias for supported data types:
- pandas.DataFrame, pandas.Series
- polars.DataFrame, polars.Series  
- numpy.ndarray, numpy.generic
- pandas.Styler (styled DataFrames)
"""

# JavaScript integration
class JavascriptFunction(str):
    """
    String subclass for JavaScript function code that will be evaluated.
    Functions must start with 'function(' pattern.
    
    Usage: JavascriptFunction("function(data) { return data.length; }")
    
    Security Warning: Only use with trusted code.
    """

class JavascriptCode(str):
    """
    String subclass for JavaScript code snippets that will be evaluated.
    
    Usage: JavascriptCode("console.log('Hello from ITables');")
    
    Security Warning: Only use with trusted code.
    """

Configuration Type Definitions

Structured type definitions for all configuration options, providing complete specification of available parameters and their expected types.

class ITableOptions(TypedDict):
    """
    Configuration options for show() function and ITable components.
    All options are optional (NotRequired).
    """
    
    # Display and styling
    classes: str | list[str]  # CSS classes for table styling
    style: str | dict[str, str]  # CSS styles for table appearance
    selected_rows: list[int]  # Pre-selected row indices
    
    # Index and data control
    showIndex: bool | str  # Index display control ("auto", True, False)
    maxBytes: int | str  # Maximum data size before downsampling
    maxRows: int  # Maximum rows before downsampling
    maxColumns: int  # Maximum columns before downsampling
    
    # Content handling
    allow_html: bool  # Allow HTML content in table cells
    table_id: str  # Custom HTML table ID
    
    # DataTables library configuration
    dt_url: str  # DataTables JavaScript bundle URL
    dt_bundle: str | Path  # Local DataTables bundle path
    connected: bool  # Load from CDN vs offline bundle
    display_logo_when_loading: bool  # Show ITables logo while loading
    
    # Table features
    footer: bool  # Show table footer
    column_filters: str | bool  # Column filtering UI ("header", "footer", False)
    text_in_header_can_be_selected: bool  # Header text selectability
    
    # Behavior and warnings
    warn_on_unexpected_types: bool  # Warn about unexpected data types
    warn_on_selected_rows_not_rendered: bool  # Warn about selection issues
    warn_on_undocumented_option: bool  # Warn about unknown options
    warn_on_unexpected_option_type: bool  # Warn about type mismatches
    
    # Advanced rendering
    use_to_html: bool  # Use DataFrame.to_html() instead of JSON serialization

class DTForITablesOptions(TypedDict):
    """
    Options passed to DataTable constructor in framework extensions.
    Subset of ITableOptions with additional internal parameters.
    """
    
    # Table content and structure
    caption: str  # Table caption text
    classes: str | list[str]  # CSS classes
    style: str | dict[str, str]  # CSS styles
    data_json: str  # JSON-serialized table data
    table_html: str  # Pre-rendered HTML table structure
    table_style: str  # CSS styles for styled DataFrames
    
    # Selection and interaction
    selected_rows: list[int]  # Selected row indices
    filtered_row_count: int  # Number of rows filtered by downsampling
    
    # Status and messaging
    downsampling_warning: str  # Warning message for downsampled data
    text_in_header_can_be_selected: bool  # Header text selectability
    column_filters: str | bool  # Column filtering configuration
    keys_to_be_evaluated: list[list[int | str]]  # JavaScript evaluation keys
    
    # Internal options (used in templates, not passed to DataTables)
    connected: bool  # Library loading mode
    dt_url: str  # DataTables bundle URL
    display_logo_when_loading: bool  # Loading logo display

class DataTableOptions(TypedDict):
    """
    Native DataTables.net configuration options.
    See https://datatables.net/reference/option/ for complete documentation.
    """
    
    # Pagination and display
    lengthMenu: list | list[list]  # Page length options
    pageLength: int  # Default page length
    
    # Sorting and ordering
    order: list[list] | dict  # Default sort configuration
    ordering: bool | dict[str, bool]  # Enable/disable sorting
    
    # Layout and positioning
    layout: dict[str, str | dict | None]  # Control positioning
    
    # Column configuration
    columnDefs: list[dict]  # Column-specific settings
    
    # Appearance and behavior
    autoWidth: bool  # Automatic column width calculation
    scrollX: bool  # Horizontal scrolling
    scrollY: str  # Vertical scrolling height
    scrollCollapse: bool  # Collapse scrolling container
    paging: bool  # Enable pagination
    
    # Localization
    language: dict[str, str]  # UI text customization
    
    # Search functionality
    search: dict  # Global search configuration
    searchCols: list  # Column-specific search
    
    # State management
    stateSave: bool  # Save table state
    stateDuration: int  # State persistence duration
    
    # Callbacks (JavaScript functions)
    initComplete: JavascriptFunction  # Initialization complete callback
    fnInfoCallback: JavascriptFunction  # Info display callback
    drawCallback: JavascriptFunction  # Table draw callback
    
    # Extensions
    buttons: list[str | dict]  # Export/action buttons
    columnControl: Any  # Column visibility control
    fixedColumns: dict[str, int]  # Fixed column configuration
    searchPanes: dict  # Search panes extension
    searchBuilder: dict  # Search builder extension
    rowGroup: dict  # Row grouping extension
    select: bool | str | dict  # Row selection configuration
    keys: bool  # Keyboard navigation

Validation and Type Checking

Functions for runtime validation and type checking of configuration options, providing development-time feedback and ensuring configuration correctness.

def check_itable_arguments(kwargs, typed_dict):
    """
    Validate arguments against TypedDict specification.

    Parameters:
    - kwargs (dict): Arguments to validate
    - typed_dict (type): TypedDict class for validation

    Returns:
    None (raises exceptions or emits warnings for invalid arguments)
    """

def is_typeguard_available():
    """
    Check if typeguard package is available for advanced type checking.

    Returns:
    bool: True if typeguard >= 4.4.1 is available, False otherwise
    """

def check_itable_argument_names(names, typed_dict):
    """
    Validate that argument names are documented in TypedDict.

    Parameters:
    - names (set[str]): Argument names to check
    - typed_dict (type): TypedDict class for validation

    Returns:
    None (emits warnings for undocumented arguments)
    """

def check_itable_argument_types(kwargs, typed_dict):
    """
    Validate argument types against TypedDict specification.
    Requires typeguard package.

    Parameters:
    - kwargs (dict): Arguments with values to type-check
    - typed_dict (type): TypedDict class for validation

    Returns:
    None (emits warnings for type mismatches)
    """

Usage Examples

Basic Type Usage

from itables import show
from itables.typing import DataFrameOrSeries, ITableOptions
import pandas as pd

# Type-annotated function
def display_data(df: DataFrameOrSeries, options: ITableOptions) -> None:
    show(df, **options)

# Usage with proper typing
df = pd.DataFrame({'A': [1, 2, 3], 'B': ['x', 'y', 'z']})
config: ITableOptions = {
    'pageLength': 10,
    'classes': 'display compact',
    'column_filters': 'header'
}

display_data(df, config)

JavaScript Integration

from itables.typing import JavascriptFunction, JavascriptCode
from itables import show

# Custom JavaScript function for formatting
format_function = JavascriptFunction("""
function(data, type, row) {
    if (type === 'display' && data > 100) {
        return '<span style="color: red;">' + data + '</span>';
    }
    return data;
}
""")

# Custom initialization code
init_code = JavascriptCode("""
console.log('Table initialized with custom styling');
$('#myTable').addClass('custom-highlight');
""")

# Use in table configuration
show(df,
     columnDefs=[{
         'targets': [1],  # Target second column
         'render': format_function
     }],
     initComplete=JavascriptFunction("""
     function(settings, json) {
         console.log('Table ready with', json.recordsTotal, 'records');
     }
     """))

Type Validation

from itables.typing import check_itable_arguments, ITableOptions
import itables.options as opts

# Enable validation warnings
opts.warn_on_undocumented_option = True
opts.warn_on_unexpected_option_type = True

# This will trigger validation warnings
invalid_config = {
    'pageLength': '10',  # Should be int, not str
    'unknown_option': True,  # Not documented in ITableOptions
    'classes': 123  # Should be str or list[str], not int
}

# Validation occurs automatically in show()
show(df, **invalid_config)  # Emits warnings

Advanced Configuration Types

from typing import TypedDict
from itables.typing import ITableOptions, JavascriptFunction

# Custom configuration with type safety
class CustomTableConfig(TypedDict):
    basic_options: ITableOptions
    advanced_features: dict[str, any]

# DataTables extension configuration
search_builder_config = {
    'searchBuilder': {
        'columns': [0, 1, 2],
        'conditions': {
            'string': ['=', '!=', 'starts', 'contains'],
            'number': ['=', '!=', '<', '>', 'between']
        }
    }
}

# Export buttons configuration
export_config = {
    'buttons': [
        'copy',
        {
            'extend': 'csv',
            'text': 'Export CSV',
            'filename': 'data_export'
        },
        {
            'extend': 'excel',
            'text': 'Export Excel'
        }
    ]
}

show(df, **search_builder_config, **export_config)

Framework-Specific Types

# Dash component with proper typing
from itables.dash import ITable, ITableOutputs
from dash import callback, Input, Output

@callback(
    Output('output-div', 'children'),
    Input('my-table', 'selected_rows')
)
def update_output(selected_rows: list[int]) -> str:
    if selected_rows:
        return f"Selected {len(selected_rows)} rows"
    return "No selection"

# Widget with type annotations
from itables.widget import ITable as WidgetITable

def create_widget(df: DataFrameOrSeries) -> WidgetITable:
    return WidgetITable(
        df=df,
        pageLength=20,
        select={'style': 'multi'}
    )

Type Safety Best Practices

Configuration Validation

# Use type checking during development
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from itables.typing import ITableOptions

def safe_show(df, **kwargs):
    """Type-safe wrapper for show() function."""
    # Runtime validation
    from itables.typing import check_itable_arguments, ITableOptions
    check_itable_arguments(kwargs, ITableOptions)
    
    # Display table
    from itables import show
    show(df, **kwargs)

JavaScript Safety

from itables.typing import JavascriptFunction

def create_safe_callback(code: str) -> JavascriptFunction:
    """Create JavaScript callback with basic validation."""
    if not code.strip().startswith('function('):
        raise ValueError("JavaScript function must start with 'function('")
    
    return JavascriptFunction(code)

# Usage
callback = create_safe_callback("""
function(settings, json) {
    console.log('Callback executed safely');
}
""")

Extension Development

from typing import Protocol
from itables.typing import DataFrameOrSeries, ITableOptions

class TableRenderer(Protocol):
    """Protocol for table rendering implementations."""
    
    def render(self, df: DataFrameOrSeries, **kwargs: ITableOptions) -> str:
        """Render DataFrame as HTML table."""
        ...

class CustomRenderer:
    """Custom table renderer implementing the protocol."""
    
    def render(self, df: DataFrameOrSeries, **kwargs: ITableOptions) -> str:
        # Custom rendering logic
        return f"<div>Custom table with {len(df)} rows</div>"

Install with Tessl CLI

npx tessl i tessl/pypi-itables

docs

configuration.md

core-display.md

data-utilities.md

framework-extensions.md

index.md

type-system.md

tile.json