Skip to content

Commit 237174f

Browse files
committed
Add type support for serialize_numpy_dtype(); Determine default sorting direction
1 parent f71e8b6 commit 237174f

File tree

2 files changed

+35
-13
lines changed

2 files changed

+35
-13
lines changed

shiny/render/_data_frame.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -939,9 +939,8 @@ async def update_sort(
939939
Parameters
940940
----------
941941
sort
942-
A list of column sorting information. If `None`, sorting will be removed.
942+
A list of column sorting information. If `None`, sorting will be removed. `int` values will be upgraded to `{"col": int, "desc": <DESC>}` where `<DESC>` is `True` if the column is number like and `False` otherwise.
943943
"""
944-
print("update_sort", sort)
945944
if sort is None:
946945
sort = ()
947946
elif isinstance(sort, int):
@@ -960,6 +959,12 @@ async def update_sort(
960959
ncol = len(data.columns)
961960

962961
for val in sort:
962+
val_dict: ColumnSort
963+
if isinstance(val, int):
964+
965+
col: pd.Series[Any] = data[val]
966+
desc = serialize_numpy_dtype(col)["type"] == "numeric"
967+
val_dict = {"col": val, "desc": desc}
963968
val_dict: ColumnSort = (
964969
val if isinstance(val, dict) else {"col": val, "desc": True}
965970
)

shiny/render/_data_frame_utils/_unsafe.py

Lines changed: 28 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,11 @@
66

77
from __future__ import annotations
88

9-
from typing import TYPE_CHECKING, Any, Protocol, runtime_checkable
9+
from typing import TYPE_CHECKING, Any, Literal, Protocol, runtime_checkable
1010

1111
from htmltools import HTML, MetadataNode, Tagifiable
1212

13-
from ..._typing_extensions import TypeGuard
13+
from ..._typing_extensions import TypedDict, TypeGuard
1414

1515
if TYPE_CHECKING:
1616
import pandas as pd
@@ -22,7 +22,25 @@
2222
# pyright: reportUnknownVariableType=false
2323

2424

25-
def serialize_numpy_dtypes(df: "pd.DataFrame") -> list[dict[str, Any]]:
25+
class DataFrameDtypeOriginal(TypedDict):
26+
type: str
27+
28+
29+
class DataFrameDtypeSubset(TypedDict):
30+
type: Literal["numeric", "string", "html", "unknown"]
31+
32+
33+
class DataFrameDtypeCategories(TypedDict):
34+
type: Literal["categorical"]
35+
categories: list[str]
36+
37+
38+
DataFrameDtype = (
39+
DataFrameDtypeOriginal | DataFrameDtypeSubset | DataFrameDtypeCategories
40+
)
41+
42+
43+
def serialize_numpy_dtypes(df: "pd.DataFrame") -> list[DataFrameDtype]:
2644
return [serialize_numpy_dtype(col) for _, col in df.items()]
2745

2846

@@ -31,17 +49,15 @@ def col_contains_shiny_html(col: "pd.Series") -> bool:
3149

3250

3351
def serialize_numpy_dtype(
34-
col: "pd.Series",
35-
) -> dict[str, Any]:
52+
col: "pd.Series[Any]",
53+
) -> DataFrameDtypeOriginal | DataFrameDtypeSubset | DataFrameDtypeCategories:
3654
import pandas as pd
3755

3856
t = pd.api.types.infer_dtype(col)
3957
# t can be any of: string, bytes, floating, integer, mixed-integer,
4058
# mixed-integer-float, decimal, complex, categorical, boolean, datetime64,
4159
# datetime, date, timedelta64, timedelta, time, period, mixed, unknown-array
4260

43-
res: dict[str, Any] = {}
44-
4561
if t == "string":
4662
if col_contains_shiny_html(col):
4763
t = "html"
@@ -51,16 +67,17 @@ def serialize_numpy_dtype(
5167
elif t in ["bytes", "floating", "integer", "decimal", "mixed-integer-float"]:
5268
t = "numeric"
5369
elif t == "categorical":
54-
res["categories"] = [str(x) for x in col.cat.categories.to_list()]
70+
return {
71+
"type": "categorical",
72+
"categories": [str(x) for x in col.cat.categories.to_list()],
73+
}
5574
else:
5675
if col_contains_shiny_html(col):
5776
t = "html"
5877
else:
5978
t = "unknown"
6079

61-
res["type"] = t
62-
63-
return res
80+
return {"type": t}
6481

6582

6683
# TODO-future; Replace this class with `htmltools.ReprHtml` when it is publically available. Even better... there should be a "is tag-like" method in htmltools that determines if the object could be enhanced by rendering

0 commit comments

Comments
 (0)