diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 3d9eb4e96f78a..b3eabf3552a75 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -157,53 +157,40 @@ def __init__( na_rep: Optional[str] = None, uuid_len: int = 5, ): - self.ctx: DefaultDict[Tuple[int, int], List[str]] = defaultdict(list) - self._todo: List[Tuple[Callable, Tuple, Dict]] = [] - + # validate ordered args if not isinstance(data, (pd.Series, pd.DataFrame)): raise TypeError("``data`` must be a Series or DataFrame") if data.ndim == 1: data = data.to_frame() if not data.index.is_unique or not data.columns.is_unique: raise ValueError("style is not supported for non-unique indices.") - - self.data = data - self.index = data.index - self.columns = data.columns - + assert isinstance(data, DataFrame) + self.data: DataFrame = data + self.index: pd.Index = data.index + self.columns: pd.Index = data.columns + if precision is None: + precision = get_option("display.precision") + self.precision = precision + self.table_styles = table_styles if not isinstance(uuid_len, int) or not uuid_len >= 0: raise TypeError("``uuid_len`` must be an integer in range [0, 32].") self.uuid_len = min(32, uuid_len) self.uuid = (uuid or uuid4().hex[: self.uuid_len]) + "_" - self.table_styles = table_styles self.caption = caption - if precision is None: - precision = get_option("display.precision") - self.precision = precision self.table_attributes = table_attributes - self.hidden_index = False - self.hidden_columns: Sequence[int] = [] self.cell_ids = cell_ids self.na_rep = na_rep - self.tooltips: Optional[_Tooltips] = None - + # assign additional default vars + self.hidden_index: bool = False + self.hidden_columns: Sequence[int] = [] + self.ctx: DefaultDict[Tuple[int, int], List[str]] = defaultdict(list) self.cell_context: Dict[str, Any] = {} - - # display_funcs maps (row, col) -> formatting function - - def default_display_func(x): - if self.na_rep is not None and pd.isna(x): - return self.na_rep - elif is_float(x): - display_format = f"{x:.{self.precision}f}" - return display_format - else: - return x - - self._display_funcs: DefaultDict[ + self._todo: List[Tuple[Callable, Tuple, Dict]] = [] + self.tooltips: Optional[_Tooltips] = None + self._display_funcs: DefaultDict[ # maps (row, col) -> formatting function Tuple[int, int], Callable[[Any], str] - ] = defaultdict(lambda: default_display_func) + ] = defaultdict(lambda: self._default_display_func) def _repr_html_(self) -> str: """ @@ -224,6 +211,15 @@ def _init_tooltips(self): if self.tooltips is None: self.tooltips = _Tooltips() + def _default_display_func(self, x): + if self.na_rep is not None and pd.isna(x): + return self.na_rep + elif is_float(x): + display_format = f"{x:.{self.precision}f}" + return display_format + else: + return x + def set_tooltips(self, ttips: DataFrame) -> Styler: """ Add string based tooltips that will appear in the `Styler` HTML result. These