Skip to content

Commit

Permalink
TYP: Reviewing it the second time as simonjayhawkins suggested
Browse files Browse the repository at this point in the history
  • Loading branch information
MomIsBestFriend committed Dec 25, 2019
1 parent e260973 commit 9e9e4c7
Showing 1 changed file with 45 additions and 30 deletions.
75 changes: 45 additions & 30 deletions pandas/io/formats/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,13 +25,13 @@

from pandas._config import get_option

from pandas._typing import Axis, FrameOrSeries
from pandas.compat._optional import import_optional_dependency
from pandas.util._decorators import Appender

from pandas.core.dtypes.common import is_float

import pandas as pd
from pandas._typing import Axis, FrameOrSeries
from pandas.api.types import is_dict_like, is_list_like
import pandas.core.common as com
from pandas.core.generic import _shared_docs
Expand All @@ -51,7 +51,7 @@


@contextmanager
def _mpl(func):
def _mpl(func: Callable):
if has_mpl:
yield plt, colors
else:
Expand Down Expand Up @@ -135,9 +135,9 @@ class Styler:

def __init__(
self,
data,
data: FrameOrSeries,
precision: Optional[int] = None,
table_styles=None,
table_styles: Union[List[Dict[str, List[Tuple[str, str]]]], None] = None,
uuid: Optional[str] = None,
caption: Optional[str] = None,
table_attributes: Optional[str] = None,
Expand Down Expand Up @@ -185,7 +185,7 @@ def default_display_func(x):
Tuple[int, int], Callable[[Any], str]
] = defaultdict(lambda: default_display_func)

def _repr_html_(self):
def _repr_html_(self) -> str:
"""
Hooks into Jupyter notebook rich display system.
"""
Expand Down Expand Up @@ -221,7 +221,7 @@ def to_excel(
inf_rep: str = "inf",
verbose: bool = True,
freeze_panes: Optional[Tuple[int, int]] = None,
):
) -> None:

from pandas.io.formats.excel import ExcelFormatter

Expand All @@ -245,7 +245,7 @@ def to_excel(
engine=engine,
)

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

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

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

cell_context = dict()
cell_context: Dict = dict()

n_rlvls = self.data.index.nlevels
n_clvls = self.data.columns.nlevels
Expand Down Expand Up @@ -555,16 +555,18 @@ def render(self, **kwargs) -> str:
d.update(kwargs)
return self.template.render(**d)

def _update_ctx(self, attrs) -> None:
def _update_ctx(self, attrs: FrameOrSeries) -> None:
"""
Update the state of the Styler.
Collects a mapping of {index_label: ['<property>: <value>']}.
Parameters
----------
attrs : Series or DataFrame
should contain strings of '<property>: <value>;<prop2>: <val2>'
Whitespace shouldn't matter and the final trailing ';' shouldn't
matter.
should contain strings of '<property>: <value>;<prop2>: <val2>'
Whitespace shouldn't matter and the final trailing ';' shouldn't
matter.
"""
for row_label, v in attrs.iterrows():
for col_label, col in v.items():
Expand All @@ -573,7 +575,7 @@ def _update_ctx(self, attrs) -> None:
for pair in col.rstrip(";").split(";"):
self.ctx[(i, j)].append(pair)

def _copy(self, deepcopy: bool = False):
def _copy(self, deepcopy: bool = False) -> "Styler":
styler = Styler(
self.data,
precision=self.precision,
Expand All @@ -590,16 +592,16 @@ def _copy(self, deepcopy: bool = False):
styler._todo = self._todo
return styler

def __copy__(self):
def __copy__(self) -> "Styler":
"""
Deep copy by default.
"""
return self._copy(deepcopy=False)

def __deepcopy__(self, memo):
def __deepcopy__(self, memo) -> "Styler":
return self._copy(deepcopy=True)

def clear(self):
def clear(self) -> None:
"""
Reset the styler, removing any previously applied styles.
Expand All @@ -622,7 +624,9 @@ def _compute(self):
r = func(self)(*args, **kwargs)
return r

def _apply(self, func, axis: Optional[Axis] = 0, subset=None, **kwargs) -> "Styler":
def _apply(
self, func: Callable, axis: Optional[Axis] = 0, subset=None, **kwargs
) -> "Styler":
subset = slice(None) if subset is None else subset
subset = _non_reducing_slice(subset)
data = self.data.loc[subset]
Expand Down Expand Up @@ -655,7 +659,9 @@ def _apply(self, func, axis: Optional[Axis] = 0, subset=None, **kwargs) -> "Styl
self._update_ctx(result)
return self

def apply(self, func, axis: Optional[Axis] = 0, subset=None, **kwargs) -> "Styler":
def apply(
self, func: Callable, axis: Optional[Axis] = 0, subset=None, **kwargs
) -> "Styler":
"""
Apply a function column-wise, row-wise, or table-wise.
Expand Down Expand Up @@ -706,7 +712,7 @@ def apply(self, func, axis: Optional[Axis] = 0, subset=None, **kwargs) -> "Style
)
return self

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

def applymap(self, func, subset=None, **kwargs) -> "Styler":
def applymap(self, func: Callable, subset=None, **kwargs) -> "Styler":
"""
Apply a function elementwise.
Expand Down Expand Up @@ -745,7 +751,12 @@ def applymap(self, func, subset=None, **kwargs) -> "Styler":
return self

def where(
self, cond, value: str, other: Optional[str] = None, subset=None, **kwargs
self,
cond: Callable,
value: str,
other: Optional[str] = None,
subset=None,
**kwargs,
) -> "Styler":
"""
Apply a function elementwise.
Expand Down Expand Up @@ -823,7 +834,7 @@ def set_table_attributes(self, attributes: str) -> "Styler":
self.table_attributes = attributes
return self

def export(self) -> List:
def export(self) -> List[Tuple[Callable, Tuple, Dict]]:
"""
Export the styles to applied to the current Styler.
Expand All @@ -839,7 +850,7 @@ def export(self) -> List:
"""
return self._todo

def use(self, styles: List) -> "Styler":
def use(self, styles: List[Tuple[Callable, Tuple, Dict]]) -> "Styler":
"""
Set the styles on the current Styler.
Expand Down Expand Up @@ -891,7 +902,9 @@ def set_caption(self, caption: str) -> "Styler":
self.caption = caption
return self

def set_table_styles(self, table_styles: List) -> "Styler":
def set_table_styles(
self, table_styles: List[Dict[str, List[Tuple[str, str]]]]
) -> "Styler":
"""
Set the table styles on a Styler.
Expand Down Expand Up @@ -1170,8 +1183,8 @@ def set_properties(self, subset=None, **kwargs) -> "Styler":
def _bar(
s,
align: str,
colors,
width=100,
colors: List[str],
width: float = 100,
vmin: Optional[float] = None,
vmax: Optional[float] = None,
):
Expand All @@ -1192,7 +1205,7 @@ def _bar(
normed = width * (s.to_numpy(dtype=float) - smin) / (smax - smin + 1e-12)
zero = -width * smin / (smax - smin + 1e-12)

def css_bar(start, end, color):
def css_bar(start: float, end: float, color: str) -> str:
"""
Generate CSS code to draw a bar from start to end.
"""
Expand Down Expand Up @@ -1417,7 +1430,7 @@ class MyStyler(cls):

return MyStyler

def pipe(self, func, *args, **kwargs):
def pipe(self, func: Callable, *args, **kwargs):
"""
Apply ``func(self, *args, **kwargs)``, and return the result.
Expand Down Expand Up @@ -1540,7 +1553,9 @@ def _get_level_lengths(index, hidden_elements=None):
return non_zero_lengths


def _maybe_wrap_formatter(formatter, na_rep: Optional[str]):
def _maybe_wrap_formatter(
formatter: Union[Callable, str], na_rep: Optional[str]
) -> Callable:
if isinstance(formatter, str):
formatter_func = lambda x: formatter.format(x)
elif callable(formatter):
Expand Down

0 comments on commit 9e9e4c7

Please sign in to comment.