Skip to content

Commit 9e9e4c7

Browse files
author
MomIsBestFriend
committed
TYP: Reviewing it the second time as simonjayhawkins suggested
1 parent e260973 commit 9e9e4c7

File tree

1 file changed

+45
-30
lines changed

1 file changed

+45
-30
lines changed

pandas/io/formats/style.py

Lines changed: 45 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -25,13 +25,13 @@
2525

2626
from pandas._config import get_option
2727

28+
from pandas._typing import Axis, FrameOrSeries
2829
from pandas.compat._optional import import_optional_dependency
2930
from pandas.util._decorators import Appender
3031

3132
from pandas.core.dtypes.common import is_float
3233

3334
import pandas as pd
34-
from pandas._typing import Axis, FrameOrSeries
3535
from pandas.api.types import is_dict_like, is_list_like
3636
import pandas.core.common as com
3737
from pandas.core.generic import _shared_docs
@@ -51,7 +51,7 @@
5151

5252

5353
@contextmanager
54-
def _mpl(func):
54+
def _mpl(func: Callable):
5555
if has_mpl:
5656
yield plt, colors
5757
else:
@@ -135,9 +135,9 @@ class Styler:
135135

136136
def __init__(
137137
self,
138-
data,
138+
data: FrameOrSeries,
139139
precision: Optional[int] = None,
140-
table_styles=None,
140+
table_styles: Union[List[Dict[str, List[Tuple[str, str]]]], None] = None,
141141
uuid: Optional[str] = None,
142142
caption: Optional[str] = None,
143143
table_attributes: Optional[str] = None,
@@ -185,7 +185,7 @@ def default_display_func(x):
185185
Tuple[int, int], Callable[[Any], str]
186186
] = defaultdict(lambda: default_display_func)
187187

188-
def _repr_html_(self):
188+
def _repr_html_(self) -> str:
189189
"""
190190
Hooks into Jupyter notebook rich display system.
191191
"""
@@ -221,7 +221,7 @@ def to_excel(
221221
inf_rep: str = "inf",
222222
verbose: bool = True,
223223
freeze_panes: Optional[Tuple[int, int]] = None,
224-
):
224+
) -> None:
225225

226226
from pandas.io.formats.excel import ExcelFormatter
227227

@@ -245,7 +245,7 @@ def to_excel(
245245
engine=engine,
246246
)
247247

248-
def _translate(self):
248+
def _translate(self) -> Dict:
249249
"""
250250
Convert the DataFrame in `self.data` and the attrs from `_build_styles`
251251
into a dictionary of {head, body, uuid, cellstyle}.
@@ -265,14 +265,14 @@ def _translate(self):
265265
BLANK_CLASS = "blank"
266266
BLANK_VALUE = ""
267267

268-
def format_attr(pair) -> str:
268+
def format_attr(pair: Dict[str, str]) -> str:
269269
return "{key}={value}".format(**pair)
270270

271271
# for sparsifying a MultiIndex
272272
idx_lengths = _get_level_lengths(self.index)
273273
col_lengths = _get_level_lengths(self.columns, hidden_columns)
274274

275-
cell_context = dict()
275+
cell_context: Dict = dict()
276276

277277
n_rlvls = self.data.index.nlevels
278278
n_clvls = self.data.columns.nlevels
@@ -555,16 +555,18 @@ def render(self, **kwargs) -> str:
555555
d.update(kwargs)
556556
return self.template.render(**d)
557557

558-
def _update_ctx(self, attrs) -> None:
558+
def _update_ctx(self, attrs: FrameOrSeries) -> None:
559559
"""
560560
Update the state of the Styler.
561561
562562
Collects a mapping of {index_label: ['<property>: <value>']}.
563563
564+
Parameters
565+
----------
564566
attrs : Series or DataFrame
565-
should contain strings of '<property>: <value>;<prop2>: <val2>'
566-
Whitespace shouldn't matter and the final trailing ';' shouldn't
567-
matter.
567+
should contain strings of '<property>: <value>;<prop2>: <val2>'
568+
Whitespace shouldn't matter and the final trailing ';' shouldn't
569+
matter.
568570
"""
569571
for row_label, v in attrs.iterrows():
570572
for col_label, col in v.items():
@@ -573,7 +575,7 @@ def _update_ctx(self, attrs) -> None:
573575
for pair in col.rstrip(";").split(";"):
574576
self.ctx[(i, j)].append(pair)
575577

576-
def _copy(self, deepcopy: bool = False):
578+
def _copy(self, deepcopy: bool = False) -> "Styler":
577579
styler = Styler(
578580
self.data,
579581
precision=self.precision,
@@ -590,16 +592,16 @@ def _copy(self, deepcopy: bool = False):
590592
styler._todo = self._todo
591593
return styler
592594

593-
def __copy__(self):
595+
def __copy__(self) -> "Styler":
594596
"""
595597
Deep copy by default.
596598
"""
597599
return self._copy(deepcopy=False)
598600

599-
def __deepcopy__(self, memo):
601+
def __deepcopy__(self, memo) -> "Styler":
600602
return self._copy(deepcopy=True)
601603

602-
def clear(self):
604+
def clear(self) -> None:
603605
"""
604606
Reset the styler, removing any previously applied styles.
605607
@@ -622,7 +624,9 @@ def _compute(self):
622624
r = func(self)(*args, **kwargs)
623625
return r
624626

625-
def _apply(self, func, axis: Optional[Axis] = 0, subset=None, **kwargs) -> "Styler":
627+
def _apply(
628+
self, func: Callable, axis: Optional[Axis] = 0, subset=None, **kwargs
629+
) -> "Styler":
626630
subset = slice(None) if subset is None else subset
627631
subset = _non_reducing_slice(subset)
628632
data = self.data.loc[subset]
@@ -655,7 +659,9 @@ def _apply(self, func, axis: Optional[Axis] = 0, subset=None, **kwargs) -> "Styl
655659
self._update_ctx(result)
656660
return self
657661

658-
def apply(self, func, axis: Optional[Axis] = 0, subset=None, **kwargs) -> "Styler":
662+
def apply(
663+
self, func: Callable, axis: Optional[Axis] = 0, subset=None, **kwargs
664+
) -> "Styler":
659665
"""
660666
Apply a function column-wise, row-wise, or table-wise.
661667
@@ -706,7 +712,7 @@ def apply(self, func, axis: Optional[Axis] = 0, subset=None, **kwargs) -> "Style
706712
)
707713
return self
708714

709-
def _applymap(self, func, subset=None, **kwargs) -> "Styler":
715+
def _applymap(self, func: Callable, subset=None, **kwargs) -> "Styler":
710716
func = partial(func, **kwargs) # applymap doesn't take kwargs?
711717
if subset is None:
712718
subset = pd.IndexSlice[:]
@@ -715,7 +721,7 @@ def _applymap(self, func, subset=None, **kwargs) -> "Styler":
715721
self._update_ctx(result)
716722
return self
717723

718-
def applymap(self, func, subset=None, **kwargs) -> "Styler":
724+
def applymap(self, func: Callable, subset=None, **kwargs) -> "Styler":
719725
"""
720726
Apply a function elementwise.
721727
@@ -745,7 +751,12 @@ def applymap(self, func, subset=None, **kwargs) -> "Styler":
745751
return self
746752

747753
def where(
748-
self, cond, value: str, other: Optional[str] = None, subset=None, **kwargs
754+
self,
755+
cond: Callable,
756+
value: str,
757+
other: Optional[str] = None,
758+
subset=None,
759+
**kwargs,
749760
) -> "Styler":
750761
"""
751762
Apply a function elementwise.
@@ -823,7 +834,7 @@ def set_table_attributes(self, attributes: str) -> "Styler":
823834
self.table_attributes = attributes
824835
return self
825836

826-
def export(self) -> List:
837+
def export(self) -> List[Tuple[Callable, Tuple, Dict]]:
827838
"""
828839
Export the styles to applied to the current Styler.
829840
@@ -839,7 +850,7 @@ def export(self) -> List:
839850
"""
840851
return self._todo
841852

842-
def use(self, styles: List) -> "Styler":
853+
def use(self, styles: List[Tuple[Callable, Tuple, Dict]]) -> "Styler":
843854
"""
844855
Set the styles on the current Styler.
845856
@@ -891,7 +902,9 @@ def set_caption(self, caption: str) -> "Styler":
891902
self.caption = caption
892903
return self
893904

894-
def set_table_styles(self, table_styles: List) -> "Styler":
905+
def set_table_styles(
906+
self, table_styles: List[Dict[str, List[Tuple[str, str]]]]
907+
) -> "Styler":
895908
"""
896909
Set the table styles on a Styler.
897910
@@ -1170,8 +1183,8 @@ def set_properties(self, subset=None, **kwargs) -> "Styler":
11701183
def _bar(
11711184
s,
11721185
align: str,
1173-
colors,
1174-
width=100,
1186+
colors: List[str],
1187+
width: float = 100,
11751188
vmin: Optional[float] = None,
11761189
vmax: Optional[float] = None,
11771190
):
@@ -1192,7 +1205,7 @@ def _bar(
11921205
normed = width * (s.to_numpy(dtype=float) - smin) / (smax - smin + 1e-12)
11931206
zero = -width * smin / (smax - smin + 1e-12)
11941207

1195-
def css_bar(start, end, color):
1208+
def css_bar(start: float, end: float, color: str) -> str:
11961209
"""
11971210
Generate CSS code to draw a bar from start to end.
11981211
"""
@@ -1417,7 +1430,7 @@ class MyStyler(cls):
14171430

14181431
return MyStyler
14191432

1420-
def pipe(self, func, *args, **kwargs):
1433+
def pipe(self, func: Callable, *args, **kwargs):
14211434
"""
14221435
Apply ``func(self, *args, **kwargs)``, and return the result.
14231436
@@ -1540,7 +1553,9 @@ def _get_level_lengths(index, hidden_elements=None):
15401553
return non_zero_lengths
15411554

15421555

1543-
def _maybe_wrap_formatter(formatter, na_rep: Optional[str]):
1556+
def _maybe_wrap_formatter(
1557+
formatter: Union[Callable, str], na_rep: Optional[str]
1558+
) -> Callable:
15441559
if isinstance(formatter, str):
15451560
formatter_func = lambda x: formatter.format(x)
15461561
elif callable(formatter):

0 commit comments

Comments
 (0)