Skip to content

TYP: use from __future__ import annotations more - batch 2 #41894

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 9, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 6 additions & 10 deletions pandas/io/excel/_xlsxwriter.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,6 @@
from typing import (
Any,
Dict,
List,
Optional,
Tuple,
)
from __future__ import annotations

from typing import Any

import pandas._libs.json as json
from pandas._typing import StorageOptions
Expand All @@ -17,7 +13,7 @@ class _XlsxStyler:
# Map from openpyxl-oriented styles to flatter xlsxwriter representation
# Ordering necessary for both determinism and because some are keyed by
# prefixes of others.
STYLE_MAPPING: Dict[str, List[Tuple[Tuple[str, ...], str]]] = {
STYLE_MAPPING: dict[str, list[tuple[tuple[str, ...], str]]] = {
"font": [
(("name",), "font_name"),
(("sz",), "font_size"),
Expand Down Expand Up @@ -177,8 +173,8 @@ def __init__(
datetime_format=None,
mode: str = "w",
storage_options: StorageOptions = None,
if_sheet_exists: Optional[str] = None,
engine_kwargs: Optional[Dict[str, Any]] = None,
if_sheet_exists: str | None = None,
engine_kwargs: dict[str, Any] | None = None,
):
# Use the xlsxwriter module as the Excel writer.
from xlsxwriter import Workbook
Expand Down
10 changes: 5 additions & 5 deletions pandas/io/excel/_xlwt.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from __future__ import annotations

from typing import (
TYPE_CHECKING,
Any,
Dict,
Optional,
)

import pandas._libs.json as json
Expand All @@ -28,8 +28,8 @@ def __init__(
encoding=None,
mode: str = "w",
storage_options: StorageOptions = None,
if_sheet_exists: Optional[str] = None,
engine_kwargs: Optional[Dict[str, Any]] = None,
if_sheet_exists: str | None = None,
engine_kwargs: dict[str, Any] | None = None,
):
# Use the xlwt module as the Excel writer.
import xlwt
Expand Down Expand Up @@ -76,7 +76,7 @@ def write_cells(
wks.set_horz_split_pos(freeze_panes[0])
wks.set_vert_split_pos(freeze_panes[1])

style_dict: Dict[str, XFStyle] = {}
style_dict: dict[str, XFStyle] = {}

for cell in cells:
val, fmt = self._value_with_fmt(cell.val)
Expand Down
25 changes: 11 additions & 14 deletions pandas/io/formats/css.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
"""
Utilities for interpreting CSS from Stylers for formatting non-HTML outputs.
"""
from __future__ import annotations

import re
from typing import (
Dict,
Optional,
)
import warnings


Expand Down Expand Up @@ -91,8 +88,8 @@ class CSSResolver:
def __call__(
self,
declarations_str: str,
inherited: Optional[Dict[str, str]] = None,
) -> Dict[str, str]:
inherited: dict[str, str] | None = None,
) -> dict[str, str]:
"""
The given declarations to atomic properties.

Expand Down Expand Up @@ -140,9 +137,9 @@ def __call__(

def _update_initial(
self,
props: Dict[str, str],
inherited: Dict[str, str],
) -> Dict[str, str]:
props: dict[str, str],
inherited: dict[str, str],
) -> dict[str, str]:
# 1. resolve inherited, initial
for prop, val in inherited.items():
if prop not in props:
Expand All @@ -162,9 +159,9 @@ def _update_initial(

def _update_font_size(
self,
props: Dict[str, str],
inherited: Dict[str, str],
) -> Dict[str, str]:
props: dict[str, str],
inherited: dict[str, str],
) -> dict[str, str]:
# 2. resolve relative font size
if props.get("font-size"):
props["font-size"] = self.size_to_pt(
Expand All @@ -174,7 +171,7 @@ def _update_font_size(
)
return props

def _get_font_size(self, props: Dict[str, str]) -> Optional[float]:
def _get_font_size(self, props: dict[str, str]) -> float | None:
if props.get("font-size"):
font_size_string = props["font-size"]
return self._get_float_font_size_from_pt(font_size_string)
Expand All @@ -184,7 +181,7 @@ def _get_float_font_size_from_pt(self, font_size_string: str) -> float:
assert font_size_string.endswith("pt")
return float(font_size_string.rstrip("pt"))

def _update_other_units(self, props: Dict[str, str]) -> Dict[str, str]:
def _update_other_units(self, props: dict[str, str]) -> dict[str, str]:
font_size = self._get_font_size(props)
# 3. TODO: resolve other font-relative units
for side in self.SIDES:
Expand Down
62 changes: 29 additions & 33 deletions pandas/io/formats/excel.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,17 @@
"""
Utilities for conversion to writer-agnostic Excel representation.
"""
from __future__ import annotations

from functools import reduce
import itertools
import re
from typing import (
Callable,
Dict,
Hashable,
Iterable,
Mapping,
Optional,
Sequence,
Union,
cast,
)
import warnings
Expand Down Expand Up @@ -61,8 +59,8 @@ def __init__(
col: int,
val,
style=None,
mergestart: Optional[int] = None,
mergeend: Optional[int] = None,
mergestart: int | None = None,
mergeend: int | None = None,
):
self.row = row
self.col = col
Expand Down Expand Up @@ -135,17 +133,17 @@ class CSSToExcelConverter:
# and __call__ make use of instance attributes. We leave them as
# instancemethods so that users can easily experiment with extensions
# without monkey-patching.
inherited: Optional[Dict[str, str]]
inherited: dict[str, str] | None

def __init__(self, inherited: Optional[str] = None):
def __init__(self, inherited: str | None = None):
if inherited is not None:
self.inherited = self.compute_css(inherited)
else:
self.inherited = None

compute_css = CSSResolver()

def __call__(self, declarations_str: str) -> Dict[str, Dict[str, str]]:
def __call__(self, declarations_str: str) -> dict[str, dict[str, str]]:
"""
Convert CSS declarations to ExcelWriter style.

Expand All @@ -165,7 +163,7 @@ def __call__(self, declarations_str: str) -> Dict[str, Dict[str, str]]:
properties = self.compute_css(declarations_str, self.inherited)
return self.build_xlstyle(properties)

def build_xlstyle(self, props: Mapping[str, str]) -> Dict[str, Dict[str, str]]:
def build_xlstyle(self, props: Mapping[str, str]) -> dict[str, dict[str, str]]:
out = {
"alignment": self.build_alignment(props),
"border": self.build_border(props),
Expand All @@ -176,7 +174,7 @@ def build_xlstyle(self, props: Mapping[str, str]) -> Dict[str, Dict[str, str]]:

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

def remove_none(d: Dict[str, str]) -> None:
def remove_none(d: dict[str, str]) -> None:
"""Remove key where value is None, through nested dicts"""
for k, v in list(d.items()):
if v is None:
Expand All @@ -189,30 +187,28 @@ def remove_none(d: Dict[str, str]) -> None:
remove_none(out)
return out

def build_alignment(
self, props: Mapping[str, str]
) -> Dict[str, Optional[Union[bool, str]]]:
def build_alignment(self, props: Mapping[str, str]) -> dict[str, bool | str | None]:
# TODO: text-indent, padding-left -> alignment.indent
return {
"horizontal": props.get("text-align"),
"vertical": self._get_vertical_alignment(props),
"wrap_text": self._get_is_wrap_text(props),
}

def _get_vertical_alignment(self, props: Mapping[str, str]) -> Optional[str]:
def _get_vertical_alignment(self, props: Mapping[str, str]) -> str | None:
vertical_align = props.get("vertical-align")
if vertical_align:
return self.VERTICAL_MAP.get(vertical_align)
return None

def _get_is_wrap_text(self, props: Mapping[str, str]) -> Optional[bool]:
def _get_is_wrap_text(self, props: Mapping[str, str]) -> bool | None:
if props.get("white-space") is None:
return None
return bool(props["white-space"] not in ("nowrap", "pre", "pre-line"))

def build_border(
self, props: Mapping[str, str]
) -> Dict[str, Dict[str, Optional[str]]]:
) -> dict[str, dict[str, str | None]]:
return {
side: {
"style": self._border_style(
Expand All @@ -224,7 +220,7 @@ def build_border(
for side in ["top", "right", "bottom", "left"]
}

def _border_style(self, style: Optional[str], width: Optional[str]):
def _border_style(self, style: str | None, width: str | None):
# convert styles and widths to openxml, one of:
# 'dashDot'
# 'dashDotDot'
Expand Down Expand Up @@ -263,7 +259,7 @@ def _border_style(self, style: Optional[str], width: Optional[str]):
return "dashed"
return "mediumDashed"

def _get_width_name(self, width_input: Optional[str]) -> Optional[str]:
def _get_width_name(self, width_input: str | None) -> str | None:
width = self._width_to_float(width_input)
if width < 1e-5:
return None
Expand All @@ -273,7 +269,7 @@ def _get_width_name(self, width_input: Optional[str]) -> Optional[str]:
return "medium"
return "thick"

def _width_to_float(self, width: Optional[str]) -> float:
def _width_to_float(self, width: str | None) -> float:
if width is None:
width = "2pt"
return self._pt_to_float(width)
Expand All @@ -289,12 +285,12 @@ def build_fill(self, props: Mapping[str, str]):
if fill_color not in (None, "transparent", "none"):
return {"fgColor": self.color_to_excel(fill_color), "patternType": "solid"}

def build_number_format(self, props: Mapping[str, str]) -> Dict[str, Optional[str]]:
def build_number_format(self, props: Mapping[str, str]) -> dict[str, str | None]:
return {"format_code": props.get("number-format")}

def build_font(
self, props: Mapping[str, str]
) -> Dict[str, Optional[Union[bool, int, float, str]]]:
) -> dict[str, bool | int | float | str | None]:
font_names = self._get_font_names(props)
decoration = self._get_decoration(props)
return {
Expand All @@ -316,13 +312,13 @@ def build_font(
# 'condense': ,
}

def _get_is_bold(self, props: Mapping[str, str]) -> Optional[bool]:
def _get_is_bold(self, props: Mapping[str, str]) -> bool | None:
weight = props.get("font-weight")
if weight:
return self.BOLD_MAP.get(weight)
return None

def _get_is_italic(self, props: Mapping[str, str]) -> Optional[bool]:
def _get_is_italic(self, props: Mapping[str, str]) -> bool | None:
font_style = props.get("font-style")
if font_style:
return self.ITALIC_MAP.get(font_style)
Expand All @@ -335,12 +331,12 @@ def _get_decoration(self, props: Mapping[str, str]) -> Sequence[str]:
else:
return ()

def _get_underline(self, decoration: Sequence[str]) -> Optional[str]:
def _get_underline(self, decoration: Sequence[str]) -> str | None:
if "underline" in decoration:
return "single"
return None

def _get_shadow(self, props: Mapping[str, str]) -> Optional[bool]:
def _get_shadow(self, props: Mapping[str, str]) -> bool | None:
if "text-shadow" in props:
return bool(re.search("^[^#(]*[1-9]", props["text-shadow"]))
return None
Expand Down Expand Up @@ -371,13 +367,13 @@ def _get_font_names(self, props: Mapping[str, str]) -> Sequence[str]:
font_names.append(name)
return font_names

def _get_font_size(self, props: Mapping[str, str]) -> Optional[float]:
def _get_font_size(self, props: Mapping[str, str]) -> float | None:
size = props.get("font-size")
if size is None:
return size
return self._pt_to_float(size)

def _select_font_family(self, font_names) -> Optional[int]:
def _select_font_family(self, font_names) -> int | None:
family = None
for name in font_names:
family = self.FAMILY_MAP.get(name)
Expand All @@ -386,7 +382,7 @@ def _select_font_family(self, font_names) -> Optional[int]:

return family

def color_to_excel(self, val: Optional[str]) -> Optional[str]:
def color_to_excel(self, val: str | None) -> str | None:
if val is None:
return None

Expand Down Expand Up @@ -463,14 +459,14 @@ def __init__(
self,
df,
na_rep: str = "",
float_format: Optional[str] = None,
cols: Optional[Sequence[Hashable]] = None,
header: Union[Sequence[Hashable], bool] = True,
float_format: str | None = None,
cols: Sequence[Hashable] | None = None,
header: Sequence[Hashable] | bool = True,
index: bool = True,
index_label: Optional[IndexLabel] = None,
index_label: IndexLabel | None = None,
merge_cells: bool = False,
inf_rep: str = "inf",
style_converter: Optional[Callable] = None,
style_converter: Callable | None = None,
):
self.rowcounter = 0
self.na_rep = na_rep
Expand Down
Loading