Skip to content

API reference

Auto-generated from the source docstrings.

Constructor

dt2.dt2

dt2(
    data: Any,
    columns: Optional[Sequence[ColumnSpec]] = None,
    *,
    options: Optional[dict] = None,
    server_side: bool = False,
    **kwoptions: Any
) -> Dt2

Create a :class:Dt2 table from a DataFrame or list of records.

Parameters:

Name Type Description Default
data Any

A pandas/polars DataFrame, or a list of dict rows.

required
columns Optional[Sequence[ColumnSpec]]

Optional explicit column spec (names or DataTables column dicts). When omitted, columns are inferred from data.

None
options Optional[dict]

A dict or :class:dt2.options.Options of DataTables options. Merged with any keyword options (the keyword options win on conflict).

None
server_side bool

When True, the data stays Python-side and DataTables fetches pages over the Comm (filter/order/paginate handled by :func:dt2.server.process_ssp). Use for large tables.

False
**kwoptions Any

Extra DataTables options passed verbatim (1:1 with the JS API), matching the R package's plain-list convention.

{}
Source code in src/dt2/widget.py
def dt2(
    data: Any,
    columns: Optional[Sequence[ColumnSpec]] = None,
    *,
    options: Optional[dict] = None,
    server_side: bool = False,
    **kwoptions: Any,
) -> Dt2:
    """Create a :class:`Dt2` table from a DataFrame or list of records.

    Parameters
    ----------
    data:
        A pandas/polars DataFrame, or a list of dict rows.
    columns:
        Optional explicit column spec (names or DataTables column dicts). When
        omitted, columns are inferred from ``data``.
    options:
        A dict or :class:`dt2.options.Options` of DataTables options. Merged
        with any keyword options (the keyword options win on conflict).
    server_side:
        When True, the data stays Python-side and DataTables fetches pages over
        the Comm (filter/order/paginate handled by :func:`dt2.server.process_ssp`).
        Use for large tables.
    **kwoptions:
        Extra DataTables options passed verbatim (1:1 with the JS API), matching
        the R package's plain-list convention.
    """
    rows, inferred = _rows(data)
    cols: list[ColumnSpec] = list(columns) if columns is not None else list(inferred)
    col_names = _col_data_names(cols)

    merged: dict[str, Any] = dict(options or {})
    merged.update(kwoptions)
    options = merged

    if server_side:
        return Dt2(
            data=[],
            columns=cols,
            options=options,
            server_side=True,
            _full_data=rows,
            _col_names=col_names,
        )
    return Dt2(data=rows, columns=cols, options=options)

Widget

dt2.Dt2

Bases: AnyWidget

A DataTables v2 table.

Prefer the :func:dt2 constructor, which accepts pandas/polars frames and lists of dicts and fills these traits for you.

Source code in src/dt2/widget.py
class Dt2(anywidget.AnyWidget):
    """A DataTables v2 table.

    Prefer the :func:`dt2` constructor, which accepts pandas/polars frames and
    lists of dicts and fills these traits for you.
    """

    _esm = _STATIC / "index.js"
    _css = _STATIC / "index.css"

    # Python -> JS (config)
    data = traitlets.List(default_value=[]).tag(sync=True)
    columns = traitlets.List(default_value=[]).tag(sync=True)
    options = traitlets.Dict(default_value={}).tag(sync=True)
    server_side = traitlets.Bool(False).tag(sync=True)

    # JS -> Python (events) — read these reactively in Shiny via reactive_read()
    selected_rows = traitlets.List(default_value=[]).tag(sync=True)
    state = traitlets.Dict(default_value={}).tag(sync=True)
    row_check = traitlets.Dict(default_value={}).tag(sync=True)  # {row, value, _seq}
    row_button = traitlets.Dict(default_value={}).tag(sync=True)  # {row, id, _seq}

    def __init__(self, *args: Any, **kwargs: Any) -> None:
        # Full dataset kept Python-side for server-side processing — deliberately
        # NOT a synced trait (the whole point of SSP is to not ship it all).
        self._full_data: list[dict] = kwargs.pop("_full_data", []) or []
        self._col_names: list[str] = kwargs.pop("_col_names", []) or []
        super().__init__(*args, **kwargs)
        self.on_msg(self._on_msg)

    # ---- server-side processing round-trip (Comm) ----
    def _on_msg(self, _widget: Any, content: Any, _buffers: Any) -> None:
        if not isinstance(content, dict) or not content.get("dt2_ssp"):
            return
        payload = process_ssp(content.get("request", {}), self._full_data, self._col_names)
        self.send(
            {
                "dt2_ssp_response": True,
                "requestId": content.get("requestId"),
                "payload": payload,
            }
        )

    # ---- proxy API (Python -> JS), mirrors R/dt2_proxy.R ----
    # The widget *is* the proxy here (no separate id/session like in R/Shiny);
    # call these methods on the rendered widget instance.
    def replace_data(self, data: Any) -> None:
        """Replace all table data. For server-side tables this swaps the
        Python-side dataset and triggers a client re-fetch instead."""
        rows, cols = _rows(data)
        if self.server_side:
            self._full_data = rows
            self._col_names = cols or self._col_names
            self.send({"cmd": "reload", "resetPaging": False})
        else:
            self.send({"cmd": "replaceData", "data": rows})

    def draw(self, reset_paging: bool = False) -> None:
        self.send({"cmd": "draw", "resetPaging": reset_paging})

    def reload(self, reset_paging: bool = True) -> None:
        """Re-fetch a server-side table."""
        self.send({"cmd": "reload", "resetPaging": reset_paging})

    def order(self, *specs: Sequence[Any]) -> None:
        """Reorder. Each spec is ``(col, "asc"|"desc")``; col is a 1-based index
        or a column header name (resolved client-side)."""
        self.send({"cmd": "order", "args": [[list(s) for s in specs]]})

    def search(
        self,
        value: str,
        regex: bool = False,
        smart: bool = True,
        case_insensitive: bool = True,
    ) -> None:
        self.send({"cmd": "search", "args": [value, regex, smart, case_insensitive]})

    def clear_search(self) -> None:
        self.send({"cmd": "clearSearch"})

    def page(self, action: Union[str, int] = "first", number: Optional[int] = None) -> None:
        """Navigate paging. ``action`` in first/previous/next/last/number; for
        'number', pass a 1-based ``number``."""
        self.send({"cmd": "page", "args": [action, number]})

    def select_rows(self, indexes: Sequence[int], reset: bool = True) -> None:
        """Select rows by 1-based index (Select extension)."""
        self.send({"cmd": "selectRows", "args": [list(indexes), bool(reset)]})

replace_data

replace_data(data: Any) -> None

Replace all table data. For server-side tables this swaps the Python-side dataset and triggers a client re-fetch instead.

Source code in src/dt2/widget.py
def replace_data(self, data: Any) -> None:
    """Replace all table data. For server-side tables this swaps the
    Python-side dataset and triggers a client re-fetch instead."""
    rows, cols = _rows(data)
    if self.server_side:
        self._full_data = rows
        self._col_names = cols or self._col_names
        self.send({"cmd": "reload", "resetPaging": False})
    else:
        self.send({"cmd": "replaceData", "data": rows})

draw

draw(reset_paging: bool = False) -> None
Source code in src/dt2/widget.py
def draw(self, reset_paging: bool = False) -> None:
    self.send({"cmd": "draw", "resetPaging": reset_paging})

reload

reload(reset_paging: bool = True) -> None

Re-fetch a server-side table.

Source code in src/dt2/widget.py
def reload(self, reset_paging: bool = True) -> None:
    """Re-fetch a server-side table."""
    self.send({"cmd": "reload", "resetPaging": reset_paging})

order

order(*specs: Sequence[Any]) -> None

Reorder. Each spec is (col, "asc"|"desc"); col is a 1-based index or a column header name (resolved client-side).

Source code in src/dt2/widget.py
def order(self, *specs: Sequence[Any]) -> None:
    """Reorder. Each spec is ``(col, "asc"|"desc")``; col is a 1-based index
    or a column header name (resolved client-side)."""
    self.send({"cmd": "order", "args": [[list(s) for s in specs]]})

search

search(
    value: str,
    regex: bool = False,
    smart: bool = True,
    case_insensitive: bool = True,
) -> None
Source code in src/dt2/widget.py
def search(
    self,
    value: str,
    regex: bool = False,
    smart: bool = True,
    case_insensitive: bool = True,
) -> None:
    self.send({"cmd": "search", "args": [value, regex, smart, case_insensitive]})
clear_search() -> None
Source code in src/dt2/widget.py
def clear_search(self) -> None:
    self.send({"cmd": "clearSearch"})

page

page(
    action: Union[str, int] = "first",
    number: Optional[int] = None,
) -> None

Navigate paging. action in first/previous/next/last/number; for 'number', pass a 1-based number.

Source code in src/dt2/widget.py
def page(self, action: Union[str, int] = "first", number: Optional[int] = None) -> None:
    """Navigate paging. ``action`` in first/previous/next/last/number; for
    'number', pass a 1-based ``number``."""
    self.send({"cmd": "page", "args": [action, number]})

select_rows

select_rows(
    indexes: Sequence[int], reset: bool = True
) -> None

Select rows by 1-based index (Select extension).

Source code in src/dt2/widget.py
def select_rows(self, indexes: Sequence[int], reset: bool = True) -> None:
    """Select rows by 1-based index (Select extension)."""
    self.send({"cmd": "selectRows", "args": [list(indexes), bool(reset)]})

Options builder

dt2.Options

Bases: dict

Chainable builder for DataTables v2 options (a plain dict subclass).

Pass either a DataFrame/records to seed the column-name map, or columns=[...] explicitly. The names are used only to resolve column references in the helpers; they are not emitted as a DataTables option.

Source code in src/dt2/options.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
class Options(dict):
    """Chainable builder for DataTables v2 options (a plain dict subclass).

    Pass either a DataFrame/records to seed the column-name map, or
    ``columns=[...]`` explicitly. The names are used only to resolve column
    references in the helpers; they are not emitted as a DataTables option.
    """

    def __init__(
        self,
        data: Any = None,
        *,
        columns: Optional[Sequence[str]] = None,
        **initial: Any,
    ) -> None:
        super().__init__(**initial)
        self._columns: list[str] = (
            [str(c) for c in columns] if columns is not None else _column_names(data)
        )

    # ---- internal ----
    def _add_defs(self, idx: Iterable[int], **spec: Any) -> "Options":
        defs = self.setdefault("columnDefs", [])
        for i in idx:
            defs.append({"targets": i - 1, **{k: v for k, v in spec.items()}})
        return self

    def _idx(self, cols: ColRef) -> list[int]:
        return _name_to_idx(cols, self._columns)

    # ---- ordering / search / paging (dt2_options.R) ----
    def order(self, *specs: Sequence[Any]) -> "Options":
        """Initial ordering. Each spec is ``(col, "asc"|"desc")``; col is a name
        or 1-based index."""
        ord_list = []
        for col, direction in specs:
            idx = self._idx(col)
            if idx:
                ord_list.append([idx[0] - 1, direction])
        self["order"] = ord_list
        return self

    def search_global(
        self,
        value: str,
        *,
        regex: bool = False,
        smart: bool = True,
        case_insensitive: bool = True,
    ) -> "Options":
        self["search"] = {
            "value": value,
            "regex": regex,
            "smart": smart,
            "caseInsensitive": case_insensitive,
        }
        return self

    def length_menu(
        self,
        values: Sequence[int] = (10, 25, 50, -1),
        labels: Optional[Sequence[str]] = None,
    ) -> "Options":
        values = list(values)
        if labels is not None and len(labels) == len(values):
            menu: list[Any] = []
            for v, l in zip(values, labels):
                menu.append(v if str(v) == l else {"label": l, "value": v})
            self["lengthMenu"] = menu
        else:
            self["lengthMenu"] = [int(v) for v in values]
            if -1 in values:
                lang = self.setdefault("language", {})
                lang.setdefault("lengthLabels", {})["-1"] = "All"
        return self

    def language(
        self,
        lang: Optional[dict] = None,
        *,
        url: Optional[str] = None,
    ) -> "Options":
        if url is not None:
            self["language"] = {"url": url}
        elif isinstance(lang, dict):
            self["language"] = lang
        return self

    def use_buttons(
        self,
        buttons: Sequence[str] = ("copy", "csv", "excel", "print"),
        *,
        position: str = "topEnd",
        button_class: Optional[str] = None,
    ) -> "Options":
        if button_class is not None:
            self["buttons"] = [
                {"extend": b, "className": button_class} for b in buttons
            ]
        else:
            self["buttons"] = list(buttons)
        self.setdefault("layout", {})[position] = "buttons"
        return self

    # ---- column appearance (dt2_options.R) ----
    def cols_width(self, mapping: dict) -> "Options":
        """``mapping``: ``{column_name_or_index: "120px", ...}``."""
        for name, width in mapping.items():
            self._add_defs(self._idx(name), width=width)
        return self

    def cols_align(self, cols: ColRef, align: str = "left") -> "Options":
        cls = {"left": "text-start", "center": "text-center", "right": "text-end"}
        if align not in cls:
            raise ValueError("align must be one of 'left', 'center', 'right'.")
        return self._add_defs(self._idx(cols), className=cls[align])

    def cols_hide(self, cols: ColRef) -> "Options":
        return self._add_defs(self._idx(cols), visible=False)

    def cols_escape(self, cols: ColRef, escape: bool = True) -> "Options":
        if escape:
            render = JS(
                "function(d,t){ if(t!=='display'||d==null) return d;"
                " return String(d).replace(/&/g,'&amp;').replace(/</g,'&lt;')"
                ".replace(/>/g,'&gt;').replace(/\"/g,'&quot;').replace(/'/g,'&#39;'); }"
            )
        else:
            render = JS("function(d,t){return d;}")
        return self._add_defs(self._idx(cols), render=render)

    # ---- renderers / formats (dt2_formats.R) ----
    def format_number(
        self,
        cols: ColRef,
        *,
        thousands: Optional[str] = None,
        decimal: Optional[str] = None,
        digits: int = 0,
        prefix: str = "",
        prefix_right: str = "",
    ) -> "Options":
        js = JS(
            "DataTable.render.number(%s,%s,%d,%s,%s)"
            % (
                _js_str(thousands),
                _js_str(decimal),
                int(digits),
                _js_str(prefix),
                _js_str(prefix_right),
            )
        )
        return self._add_defs(self._idx(cols), render=js)

    def format_datetime(
        self,
        cols: ColRef,
        *,
        from_: Optional[str] = None,
        to: str = "DD/MM/YYYY",
        locale: Optional[str] = None,
        default: Optional[str] = None,
    ) -> "Options":
        args = ", ".join(
            [
                _js_str(from_, "undefined"),
                _js_str(to, "undefined"),
                _js_str(locale, "undefined"),
                _js_str(default, "undefined"),
            ]
        )
        js = JS("DataTable.render.datetime(%s)" % args)
        return self._add_defs(self._idx(cols), render=js)

    def format_number_abbrev(
        self,
        cols: ColRef,
        *,
        digits: int = 1,
        locale: Optional[str] = None,
    ) -> "Options":
        d = int(digits)
        if not locale:
            code = (
                "function(d,t,row,meta){"
                "if(t!=='display'&&t!=='filter')return d;"
                "var n=Number(d);if(!isFinite(n))return d;"
                "var abs=Math.abs(n),sign=n<0?'-':'';"
                "function fmt(x){return x.toFixed(%d);}"
                "if(abs>=1e9)return sign+fmt(abs/1e9)+'B';"
                "if(abs>=1e6)return sign+fmt(abs/1e6)+'M';"
                "if(abs>=1e3)return sign+fmt(abs/1e3)+'k';"
                "return n.toFixed(%d);}" % (d, d)
            )
        else:
            loc = json.dumps(locale)
            code = (
                "function(d,t,row,meta){"
                "if(t!=='display'&&t!=='filter')return d;"
                "var n=Number(d);if(!isFinite(n))return d;"
                "var abs=Math.abs(n),sign=n<0?'-':'';"
                "function fmt(x){return Number(x.toFixed(%d)).toLocaleString(%s);}"
                "if(abs>=1e9)return sign+fmt(abs/1e9)+'B';"
                "if(abs>=1e6)return sign+fmt(abs/1e6)+'M';"
                "if(abs>=1e3)return sign+fmt(abs/1e3)+'k';"
                "return n.toLocaleString(%s,{minimumFractionDigits:%d,maximumFractionDigits:%d});}"
                % (d, loc, loc, d, d)
            )
        return self._add_defs(self._idx(cols), render=JS(code))

    def format_time_relative(self, cols: ColRef, *, locale: str = "pt-br") -> "Options":
        self["_momentLocale"] = locale
        js = JS(
            "function(d,t,row,meta){if(d==null||d==='')return d;"
            "try{if(window.moment){var m=moment(d);if(m.isValid())return m.fromNow();}}"
            "catch(e){}return d;}"
        )
        return self._add_defs(self._idx(cols), render=js)

    def cols_render(self, cols: ColRef, js_render: JS) -> "Options":
        if not isinstance(js_render, JS):
            raise TypeError("js_render must be a dt2.JS(...) instance.")
        return self._add_defs(self._idx(cols), render=js_render)

    def cols_render_orthogonal(
        self,
        cols: ColRef,
        *,
        display: Optional[JS] = None,
        sort: Optional[JS] = None,
        filter: Optional[JS] = None,
        type: Optional[JS] = None,
    ) -> "Options":
        parts = {
            k: v
            for k, v in {
                "display": display,
                "sort": sort,
                "filter": filter,
                "type": type,
            }.items()
            if v is not None
        }
        if not parts:
            raise ValueError("Provide at least one of display/sort/filter/type.")
        # nested JS markers are revived recursively client-side
        return self._add_defs(self._idx(cols), render=dict(parts))

    def use_renderer(self, cols: ColRef, name: str) -> "Options":
        js = _RENDERERS.get(name)
        if js is None:
            raise KeyError(f"Renderer {name!r} is not registered.")
        return self._add_defs(self._idx(cols), render=js)

    # ---- extension activation (Phase 2) ----
    # Each sets the DataTables option the bundled extension reads. Accept True or
    # a config dict (1:1 with the extension's option), matching the R convention.
    def _set(self, key: str, value: Any) -> "Options":
        self[key] = value
        return self

    def select(self, value: Union[bool, dict] = True) -> "Options":
        return self._set("select", value)

    def responsive(self, value: Union[bool, dict] = True) -> "Options":
        return self._set("responsive", value)

    def fixed_header(self, value: Union[bool, dict] = True) -> "Options":
        return self._set("fixedHeader", value)

    def fixed_columns(self, value: Union[bool, dict] = True) -> "Options":
        return self._set("fixedColumns", value)

    def key_table(self, value: Union[bool, dict] = True) -> "Options":
        return self._set("keys", value)

    def col_reorder(self, value: Union[bool, dict] = True) -> "Options":
        return self._set("colReorder", value)

    def row_reorder(self, value: Union[bool, dict] = True) -> "Options":
        return self._set("rowReorder", value)

    def row_group(self, data_src: Union[str, int, dict]) -> "Options":
        """Group rows by a column. Pass a column data-key/index or a full
        rowGroup config dict."""
        cfg = data_src if isinstance(data_src, dict) else {"dataSrc": data_src}
        return self._set("rowGroup", cfg)

    def scroller(self, scroll_y: str = "400px", value: Union[bool, dict] = True) -> "Options":
        """Virtual scrolling. Requires scrollY; deferRender is enabled for it."""
        self["scrollY"] = scroll_y
        self["deferRender"] = True
        return self._set("scroller", value)

    def search_panes(self, value: Union[bool, dict] = True) -> "Options":
        return self._set("searchPanes", value)

    def search_builder(self, value: Union[bool, dict] = True) -> "Options":
        return self._set("searchBuilder", value)

    def state_restore(self, value: Union[bool, dict] = True) -> "Options":
        self["stateSave"] = True
        return self._set("stateRestore", value)

    def column_control(self, value: Any = True) -> "Options":
        return self._set("columnControl", value)

    def buttons(
        self,
        buttons: Sequence[Any] = ("copyHtml5", "csvHtml5", "excelHtml5", "print"),
        *,
        target: Optional[str] = None,
    ) -> "Options":
        """Configure Buttons with full button ids/objects (port of R dt2_buttons).

        ``target`` is an optional CSS selector to relocate the rendered buttons
        container after init. For the simpler layout-based case use
        :meth:`use_buttons`. PDF export (``pdfHtml5``) needs pdfmake, which is
        not bundled."""
        self["buttons"] = list(buttons)
        if target is not None:
            # JS relocates the rendered container to this selector after init.
            self["dt2_buttons_target"] = target
        else:
            # DataTables 2.x only shows buttons referenced in the layout.
            self.setdefault("layout", {}).setdefault("topStart", "buttons")
        return self

    # ---- inline row inputs (port of R/dt2_inputs.R) ----
    def col_checkbox(
        self,
        col: ColRef,
        *,
        input_id_prefix: str = "row_chk_",
        value_col: Optional[Union[str, int]] = None,
    ) -> "Options":
        """Render a checkbox per row in ``col``. Clicks set the widget's
        ``row_check`` event ({row, value}). ``value_col`` seeds the initial
        checked state from another column (name or 1-based index)."""
        if value_col is None:
            value_js = "false"
        else:
            if isinstance(value_col, str):
                name = value_col
                idx0 = (self._columns.index(name) if name in self._columns else 0)
            else:
                idx0 = int(value_col) - 1
                name = self._columns[idx0] if 0 <= idx0 < len(self._columns) else ""
            value_js = "(Array.isArray(row) ? row[%d] : row[%s])" % (idx0, json.dumps(name))
        code = (
            "function(d,t,row,meta){ if(t!=='display') return d;"
            " var rid='%s'+(meta.row+1);"
            " var checked=%s?' checked':'';"
            " return '<input type=\"checkbox\" class=\"dt2-row-checkbox form-check-input\" id=\"'+rid+'\"'+checked+'/>'; }"
            % (input_id_prefix, value_js)
        )
        return self._add_defs(self._idx(col), render=JS(code))

    def col_button(
        self,
        col: ColRef,
        *,
        label: str = "Action",
        input_id_prefix: str = "row_btn_",
        button_class: str = "dt2-row-button btn btn-sm btn-primary",
    ) -> "Options":
        """Render an action button per row in ``col``. Clicks set the widget's
        ``row_button`` event ({row, id})."""
        import html as _html

        code = (
            "function(d,t,row,meta){ if(t!=='display') return d;"
            " var rid='%s'+(meta.row+1);"
            " return '<button type=\"button\" class=\"%s\" id=\"'+rid+'\">%s</button>'; }"
            % (input_id_prefix, button_class, _html.escape(label))
        )
        return self._add_defs(self._idx(col), render=JS(code))

order

order(*specs: Sequence[Any]) -> 'Options'

Initial ordering. Each spec is (col, "asc"|"desc"); col is a name or 1-based index.

Source code in src/dt2/options.py
def order(self, *specs: Sequence[Any]) -> "Options":
    """Initial ordering. Each spec is ``(col, "asc"|"desc")``; col is a name
    or 1-based index."""
    ord_list = []
    for col, direction in specs:
        idx = self._idx(col)
        if idx:
            ord_list.append([idx[0] - 1, direction])
    self["order"] = ord_list
    return self

cols_width

cols_width(mapping: dict) -> 'Options'

mapping: {column_name_or_index: "120px", ...}.

Source code in src/dt2/options.py
def cols_width(self, mapping: dict) -> "Options":
    """``mapping``: ``{column_name_or_index: "120px", ...}``."""
    for name, width in mapping.items():
        self._add_defs(self._idx(name), width=width)
    return self

row_group

row_group(data_src: Union[str, int, dict]) -> 'Options'

Group rows by a column. Pass a column data-key/index or a full rowGroup config dict.

Source code in src/dt2/options.py
def row_group(self, data_src: Union[str, int, dict]) -> "Options":
    """Group rows by a column. Pass a column data-key/index or a full
    rowGroup config dict."""
    cfg = data_src if isinstance(data_src, dict) else {"dataSrc": data_src}
    return self._set("rowGroup", cfg)

scroller

scroller(
    scroll_y: str = "400px", value: Union[bool, dict] = True
) -> "Options"

Virtual scrolling. Requires scrollY; deferRender is enabled for it.

Source code in src/dt2/options.py
def scroller(self, scroll_y: str = "400px", value: Union[bool, dict] = True) -> "Options":
    """Virtual scrolling. Requires scrollY; deferRender is enabled for it."""
    self["scrollY"] = scroll_y
    self["deferRender"] = True
    return self._set("scroller", value)

buttons

buttons(
    buttons: Sequence[Any] = (
        "copyHtml5",
        "csvHtml5",
        "excelHtml5",
        "print",
    ),
    *,
    target: Optional[str] = None
) -> "Options"

Configure Buttons with full button ids/objects (port of R dt2_buttons).

target is an optional CSS selector to relocate the rendered buttons container after init. For the simpler layout-based case use :meth:use_buttons. PDF export (pdfHtml5) needs pdfmake, which is not bundled.

Source code in src/dt2/options.py
def buttons(
    self,
    buttons: Sequence[Any] = ("copyHtml5", "csvHtml5", "excelHtml5", "print"),
    *,
    target: Optional[str] = None,
) -> "Options":
    """Configure Buttons with full button ids/objects (port of R dt2_buttons).

    ``target`` is an optional CSS selector to relocate the rendered buttons
    container after init. For the simpler layout-based case use
    :meth:`use_buttons`. PDF export (``pdfHtml5``) needs pdfmake, which is
    not bundled."""
    self["buttons"] = list(buttons)
    if target is not None:
        # JS relocates the rendered container to this selector after init.
        self["dt2_buttons_target"] = target
    else:
        # DataTables 2.x only shows buttons referenced in the layout.
        self.setdefault("layout", {}).setdefault("topStart", "buttons")
    return self

col_checkbox

col_checkbox(
    col: ColRef,
    *,
    input_id_prefix: str = "row_chk_",
    value_col: Optional[Union[str, int]] = None
) -> "Options"

Render a checkbox per row in col. Clicks set the widget's row_check event ({row, value}). value_col seeds the initial checked state from another column (name or 1-based index).

Source code in src/dt2/options.py
def col_checkbox(
    self,
    col: ColRef,
    *,
    input_id_prefix: str = "row_chk_",
    value_col: Optional[Union[str, int]] = None,
) -> "Options":
    """Render a checkbox per row in ``col``. Clicks set the widget's
    ``row_check`` event ({row, value}). ``value_col`` seeds the initial
    checked state from another column (name or 1-based index)."""
    if value_col is None:
        value_js = "false"
    else:
        if isinstance(value_col, str):
            name = value_col
            idx0 = (self._columns.index(name) if name in self._columns else 0)
        else:
            idx0 = int(value_col) - 1
            name = self._columns[idx0] if 0 <= idx0 < len(self._columns) else ""
        value_js = "(Array.isArray(row) ? row[%d] : row[%s])" % (idx0, json.dumps(name))
    code = (
        "function(d,t,row,meta){ if(t!=='display') return d;"
        " var rid='%s'+(meta.row+1);"
        " var checked=%s?' checked':'';"
        " return '<input type=\"checkbox\" class=\"dt2-row-checkbox form-check-input\" id=\"'+rid+'\"'+checked+'/>'; }"
        % (input_id_prefix, value_js)
    )
    return self._add_defs(self._idx(col), render=JS(code))

col_button

col_button(
    col: ColRef,
    *,
    label: str = "Action",
    input_id_prefix: str = "row_btn_",
    button_class: str = "dt2-row-button btn btn-sm btn-primary"
) -> "Options"

Render an action button per row in col. Clicks set the widget's row_button event ({row, id}).

Source code in src/dt2/options.py
def col_button(
    self,
    col: ColRef,
    *,
    label: str = "Action",
    input_id_prefix: str = "row_btn_",
    button_class: str = "dt2-row-button btn btn-sm btn-primary",
) -> "Options":
    """Render an action button per row in ``col``. Clicks set the widget's
    ``row_button`` event ({row, id})."""
    import html as _html

    code = (
        "function(d,t,row,meta){ if(t!=='display') return d;"
        " var rid='%s'+(meta.row+1);"
        " return '<button type=\"button\" class=\"%s\" id=\"'+rid+'\">%s</button>'; }"
        % (input_id_prefix, button_class, _html.escape(label))
    )
    return self._add_defs(self._idx(col), render=JS(code))

Renderers

dt2.JS

Bases: dict

A raw JavaScript expression, revived into a function client-side.

Equivalent to htmlwidgets::JS(). Serializes to {"__dt2_js__": code}; index.js compiles it with DataTable, $ and moment in scope.

Source code in src/dt2/options.py
class JS(dict):
    """A raw JavaScript expression, revived into a function client-side.

    Equivalent to ``htmlwidgets::JS()``. Serializes to ``{"__dt2_js__": code}``;
    ``index.js`` compiles it with ``DataTable``, ``$`` and ``moment`` in scope.
    """

    def __init__(self, code: str) -> None:
        if not isinstance(code, str):
            raise TypeError("JS() expects a JavaScript source string.")
        super().__init__({JS_MARKER: code})

    @property
    def code(self) -> str:
        return self[JS_MARKER]

dt2.register_renderer

register_renderer(name: str, js: JS) -> str

Register a named JS renderer for later use via Options.use_renderer.

Source code in src/dt2/options.py
def register_renderer(name: str, js: JS) -> str:
    """Register a named JS renderer for later use via Options.use_renderer."""
    if not isinstance(js, JS):
        raise TypeError("js must be a dt2.JS(...) instance.")
    _RENDERERS[name] = js
    return name

Extensions

dt2.extensions

extensions() -> list[dict]

List bundled DataTables extensions (parity with R dt2_extensions()).

All are bundled in the JS asset and activate via their option (set with the corresponding Options helper). PDF export (pdfmake) is not bundled.

Source code in src/dt2/options.py
def extensions() -> list[dict]:
    """List bundled DataTables extensions (parity with R ``dt2_extensions()``).

    All are bundled in the JS asset and activate via their option (set with the
    corresponding ``Options`` helper). PDF export (pdfmake) is not bundled.
    """
    return [dict(e) for e in _EXTENSIONS]

Server-side processing

dt2.server.process_ssp

process_ssp(
    request: dict,
    rows: Sequence[dict],
    columns: Sequence[str],
) -> dict

Filter, order and paginate rows per a DataTables SSP request.

Mirrors :func:dt2_ssp_handler in the R package: global case-insensitive substring search across all columns, cascading stable sort (last order key applied first), then paging. Returns the DataTables payload.

Source code in src/dt2/server.py
def process_ssp(
    request: dict,
    rows: Sequence[dict],
    columns: Sequence[str],
) -> dict:
    """Filter, order and paginate ``rows`` per a DataTables SSP ``request``.

    Mirrors :func:`dt2_ssp_handler` in the R package: global case-insensitive
    substring search across all columns, cascading stable sort (last order key
    applied first), then paging. Returns the DataTables payload.
    """
    draw = int(request.get("draw", 1) or 1)
    start = max(0, int(request.get("start", 0) or 0))
    length = int(request.get("length", 10) or 0)

    search = request.get("search") or {}
    search_value = (search.get("value") or "").strip()
    order = request.get("order") or []
    cols = list(columns)

    result = list(rows)
    total = len(result)

    # --- global search: case-insensitive substring across all columns ---
    if search_value:
        pat = search_value.lower()
        result = [
            r
            for r in result
            if any(pat in str(r.get(c, "")).lower() for c in cols)
        ]

    filtered = len(result)

    # --- ordering: apply in reverse so the first key dominates (stable sort) ---
    for o in reversed(order):
        try:
            col_idx = int(o.get("column", 0))
        except (TypeError, ValueError):
            continue
        if not (0 <= col_idx < len(cols)):
            continue
        name = cols[col_idx]
        descending = str(o.get("dir", "asc")).lower().startswith("desc")
        try:
            result = sorted(result, key=lambda r: _sort_key(r.get(name)), reverse=descending)
        except TypeError:
            # mixed types in the column → fall back to string comparison
            result = sorted(
                result,
                key=lambda r: (r.get(name) is None, str(r.get(name))),
                reverse=descending,
            )

    # --- paginate (length < 0 means "all", per the DataTables convention) ---
    if length >= 0:
        result = result[start : start + length]

    return {
        "draw": draw,
        "recordsTotal": total,
        "recordsFiltered": filtered,
        "data": result,
    }