Skip to content

Commit 9f97d11

Browse files
ShaharNavehWillAyd
authored andcommitted
TYP: Type hints in pandas/io/formats/excel.py (pandas-dev#30400)
1 parent d47c5a2 commit 9f97d11

File tree

1 file changed

+27
-28
lines changed

1 file changed

+27
-28
lines changed

pandas/io/formats/excel.py

+27-28
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from functools import reduce
55
import itertools
66
import re
7+
from typing import Callable, Dict, List, Optional, Sequence, Union
78
import warnings
89

910
import numpy as np
@@ -25,7 +26,9 @@ class ExcelCell:
2526
__fields__ = ("row", "col", "val", "style", "mergestart", "mergeend")
2627
__slots__ = __fields__
2728

28-
def __init__(self, row, col, val, style=None, mergestart=None, mergeend=None):
29+
def __init__(
30+
self, row: int, col: int, val, style=None, mergestart=None, mergeend=None
31+
):
2932
self.row = row
3033
self.col = col
3134
self.val = val
@@ -56,15 +59,15 @@ class CSSToExcelConverter:
5659
# instancemethods so that users can easily experiment with extensions
5760
# without monkey-patching.
5861

59-
def __init__(self, inherited=None):
62+
def __init__(self, inherited: Optional[str] = None):
6063
if inherited is not None:
6164
inherited = self.compute_css(inherited)
6265

6366
self.inherited = inherited
6467

6568
compute_css = CSSResolver()
6669

67-
def __call__(self, declarations_str: str):
70+
def __call__(self, declarations_str: str) -> Dict[str, Dict[str, str]]:
6871
"""
6972
Convert CSS declarations to ExcelWriter style.
7073
@@ -84,7 +87,7 @@ def __call__(self, declarations_str: str):
8487
properties = self.compute_css(declarations_str, self.inherited)
8588
return self.build_xlstyle(properties)
8689

87-
def build_xlstyle(self, props):
90+
def build_xlstyle(self, props: Dict[str, str]) -> Dict[str, Dict[str, str]]:
8891
out = {
8992
"alignment": self.build_alignment(props),
9093
"border": self.build_border(props),
@@ -95,7 +98,7 @@ def build_xlstyle(self, props):
9598

9699
# TODO: handle cell width and height: needs support in pandas.io.excel
97100

98-
def remove_none(d):
101+
def remove_none(d: Dict[str, str]) -> None:
99102
"""Remove key where value is None, through nested dicts"""
100103
for k, v in list(d.items()):
101104
if v is None:
@@ -118,7 +121,7 @@ def remove_none(d):
118121
# OpenXML also has 'justify', 'distributed'
119122
}
120123

121-
def build_alignment(self, props):
124+
def build_alignment(self, props) -> Dict[str, Optional[Union[bool, str]]]:
122125
# TODO: text-indent, padding-left -> alignment.indent
123126
return {
124127
"horizontal": props.get("text-align"),
@@ -130,7 +133,7 @@ def build_alignment(self, props):
130133
),
131134
}
132135

133-
def build_border(self, props):
136+
def build_border(self, props: Dict) -> Dict[str, Dict[str, str]]:
134137
return {
135138
side: {
136139
"style": self._border_style(
@@ -142,7 +145,7 @@ def build_border(self, props):
142145
for side in ["top", "right", "bottom", "left"]
143146
}
144147

145-
def _border_style(self, style, width):
148+
def _border_style(self, style: Optional[str], width):
146149
# convert styles and widths to openxml, one of:
147150
# 'dashDot'
148151
# 'dashDotDot'
@@ -191,7 +194,7 @@ def _border_style(self, style, width):
191194
return "dashed"
192195
return "mediumDashed"
193196

194-
def build_fill(self, props):
197+
def build_fill(self, props: Dict[str, str]):
195198
# TODO: perhaps allow for special properties
196199
# -excel-pattern-bgcolor and -excel-pattern-type
197200
fill_color = props.get("background-color")
@@ -215,7 +218,7 @@ def build_fill(self, props):
215218
}
216219
ITALIC_MAP = {"normal": False, "italic": True, "oblique": True}
217220

218-
def build_font(self, props):
221+
def build_font(self, props) -> Dict[str, Optional[Union[bool, int, str]]]:
219222
size = props.get("font-size")
220223
if size is not None:
221224
assert size.endswith("pt")
@@ -311,7 +314,7 @@ def build_font(self, props):
311314
"white": "FFFFFF",
312315
}
313316

314-
def color_to_excel(self, val):
317+
def color_to_excel(self, val: Optional[str]):
315318
if val is None:
316319
return None
317320
if val.startswith("#") and len(val) == 7:
@@ -323,7 +326,7 @@ def color_to_excel(self, val):
323326
except KeyError:
324327
warnings.warn(f"Unhandled color format: {repr(val)}", CSSWarning)
325328

326-
def build_number_format(self, props):
329+
def build_number_format(self, props: Dict) -> Dict[str, Optional[str]]:
327330
return {"format_code": props.get("number-format")}
328331

329332

@@ -366,15 +369,15 @@ class ExcelFormatter:
366369
def __init__(
367370
self,
368371
df,
369-
na_rep="",
370-
float_format=None,
371-
cols=None,
372-
header=True,
373-
index=True,
374-
index_label=None,
375-
merge_cells=False,
376-
inf_rep="inf",
377-
style_converter=None,
372+
na_rep: str = "",
373+
float_format: Optional[str] = None,
374+
cols: Optional[Sequence] = None,
375+
header: Union[bool, List[str]] = True,
376+
index: bool = True,
377+
index_label: Union[str, Sequence, None] = None,
378+
merge_cells: bool = False,
379+
inf_rep: str = "inf",
380+
style_converter: Optional[Callable] = None,
378381
):
379382
self.rowcounter = 0
380383
self.na_rep = na_rep
@@ -442,10 +445,8 @@ def _format_header_mi(self):
442445
if self.columns.nlevels > 1:
443446
if not self.index:
444447
raise NotImplementedError(
445-
"Writing to Excel with MultiIndex"
446-
" columns and no index "
447-
"('index'=False) is not yet "
448-
"implemented."
448+
"Writing to Excel with MultiIndex columns and no "
449+
"index ('index'=False) is not yet implemented."
449450
)
450451

451452
has_aliases = isinstance(self.header, (tuple, list, np.ndarray, Index))
@@ -540,7 +541,6 @@ def _format_header(self):
540541
return itertools.chain(gen, gen2)
541542

542543
def _format_body(self):
543-
544544
if isinstance(self.df.index, ABCMultiIndex):
545545
return self._format_hierarchical_rows()
546546
else:
@@ -716,8 +716,7 @@ def write(
716716
num_rows, num_cols = self.df.shape
717717
if num_rows > self.max_rows or num_cols > self.max_cols:
718718
raise ValueError(
719-
"This sheet is too large! Your sheet size is: "
720-
f"{num_rows}, {num_cols} "
719+
f"This sheet is too large! Your sheet size is: {num_rows}, {num_cols} "
721720
f"Max sheet size is: {self.max_rows}, {self.max_cols}"
722721
)
723722

0 commit comments

Comments
 (0)