Skip to content

STYLE: fixing linting issues (redefined-outer-name) #49762

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

71 changes: 43 additions & 28 deletions pandas/io/formats/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,24 +91,24 @@ def _mpl(func: Callable) -> Generator[tuple[Any, Any], None, None]:
####
# Shared Doc Strings

subset = """subset : label, array-like, IndexSlice, optional
subsets = """subset : label, array-like, IndexSlice, optional
A valid 2d input to `DataFrame.loc[<subset>]`, or, in the case of a 1d input
or single key, to `DataFrame.loc[:, <subset>]` where the columns are
prioritised, to limit ``data`` to *before* applying the function."""

props = """props : str, default None
properties = """props : str, default None
CSS properties to use for highlighting. If ``props`` is given, ``color``
is not used."""

color = """color : str, default '{default}'
coloring = """color : str, default '{default}'
Background color to use for highlighting."""

buf = """buf : str, path object, file-like object, optional
buffering = """buf : str, path object, file-like object, optional
String, path object (implementing ``os.PathLike[str]``), or file-like
object implementing a string ``write()`` function. If ``None``, the result is
returned as a string."""

encoding = """encoding : str, optional
encodings = """encoding : str, optional
Character encoding setting for file output (and meta tags if available).
Defaults to ``pandas.options.styler.render.encoding`` value of "utf-8"."""

Expand Down Expand Up @@ -1186,7 +1186,7 @@ def to_html(
) -> str:
...

@Substitution(buf=buf, encoding=encoding)
@Substitution(buf=buffering, encoding=encodings)
def to_html(
self,
buf: FilePath | WriteBuffer[str] | None = None,
Expand Down Expand Up @@ -1345,7 +1345,7 @@ def to_string(
) -> str:
...

@Substitution(buf=buf, encoding=encoding)
@Substitution(buf=buffering, encoding=encodings)
def to_string(
self,
buf: FilePath | WriteBuffer[str] | None = None,
Expand Down Expand Up @@ -1690,7 +1690,7 @@ def _apply(
self._update_ctx(result)
return self

@Substitution(subset=subset)
@Substitution(subset=subsets)
def apply(
self,
func: Callable,
Expand Down Expand Up @@ -1929,7 +1929,7 @@ def _applymap(
self._update_ctx(result)
return self

@Substitution(subset=subset)
@Substitution(subset=subsets)
def applymap(
self, func: Callable, subset: Subset | None = None, **kwargs
) -> Styler:
Expand Down Expand Up @@ -2685,7 +2685,7 @@ def _get_numeric_subset_default(self):
visibility across varying background colors. All text is dark if 0, and\n
light if 1, defaults to 0.408.""",
)
@Substitution(subset=subset)
@Substitution(subset=subsets)
def background_gradient(
self,
cmap: str | Colormap = "PuBu",
Expand Down Expand Up @@ -2868,7 +2868,7 @@ def text_gradient(
text_only=True,
)

@Substitution(subset=subset)
@Substitution(subset=subsets)
def set_properties(self, subset: Subset | None = None, **kwargs) -> Styler:
"""
Set defined CSS-properties to each ``<td>`` HTML element for the given subset.
Expand Down Expand Up @@ -2900,7 +2900,7 @@ def set_properties(self, subset: Subset | None = None, **kwargs) -> Styler:
values = "".join([f"{p}: {v};" for p, v in kwargs.items()])
return self.applymap(lambda x: values, subset=subset)

@Substitution(subset=subset)
@Substitution(subset=subsets)
def bar( # pylint: disable=disallowed-name
self,
subset: Subset | None = None,
Expand Down Expand Up @@ -3023,7 +3023,9 @@ def bar( # pylint: disable=disallowed-name

return self

@Substitution(subset=subset, props=props, color=color.format(default="red"))
@Substitution(
subset=subsets, props=properties, color=coloring.format(default="red")
)
def highlight_null(
self,
color: str = "red",
Expand Down Expand Up @@ -3066,7 +3068,9 @@ def f(data: DataFrame, props: str) -> np.ndarray:
props = f"background-color: {color};"
return self.apply(f, axis=None, subset=subset, props=props)

@Substitution(subset=subset, color=color.format(default="yellow"), props=props)
@Substitution(
subset=subsets, color=coloring.format(default="yellow"), props=properties
)
def highlight_max(
self,
subset: Subset | None = None,
Expand Down Expand Up @@ -3110,7 +3114,9 @@ def highlight_max(
props=props,
)

@Substitution(subset=subset, color=color.format(default="yellow"), props=props)
@Substitution(
subset=subsets, color=coloring.format(default="yellow"), props=properties
)
def highlight_min(
self,
subset: Subset | None = None,
Expand Down Expand Up @@ -3154,7 +3160,9 @@ def highlight_min(
props=props,
)

@Substitution(subset=subset, color=color.format(default="yellow"), props=props)
@Substitution(
subset=subsets, color=coloring.format(default="yellow"), props=properties
)
def highlight_between(
self,
subset: Subset | None = None,
Expand Down Expand Up @@ -3258,7 +3266,9 @@ def highlight_between(
inclusive=inclusive,
)

@Substitution(subset=subset, color=color.format(default="yellow"), props=props)
@Substitution(
subset=subsets, color=coloring.format(default="yellow"), props=properties
)
def highlight_quantile(
self,
subset: Subset | None = None,
Expand Down Expand Up @@ -3597,17 +3607,19 @@ def _background_gradient(
else: # else validate gmap against the underlying data
gmap = _validate_apply_axis_arg(gmap, "gmap", float, data)

with _mpl(Styler.background_gradient) as (plt, mpl):
with _mpl(Styler.background_gradient) as (_pyplot, _matplotlib):
smin = np.nanmin(gmap) if vmin is None else vmin
smax = np.nanmax(gmap) if vmax is None else vmax
rng = smax - smin
# extend lower / upper bounds, compresses color range
norm = mpl.colors.Normalize(smin - (rng * low), smax + (rng * high))
norm = _matplotlib.colors.Normalize(smin - (rng * low), smax + (rng * high))

if cmap is None:
rgbas = mpl.colormaps[mpl.rcParams["image.cmap"]](norm(gmap))
rgbas = _matplotlib.colormaps[_matplotlib.rcParams["image.cmap"]](
norm(gmap)
)
else:
rgbas = mpl.colormaps.get_cmap(cmap)(norm(gmap))
rgbas = _matplotlib.colormaps.get_cmap(cmap)(norm(gmap))

def relative_luminance(rgba) -> float:
"""
Expand Down Expand Up @@ -3636,10 +3648,11 @@ def css(rgba, text_only) -> str:
dark = relative_luminance(rgba) < text_color_threshold
text_color = "#f1f1f1" if dark else "#000000"
return (
f"background-color: {mpl.colors.rgb2hex(rgba)};color: {text_color};"
f"background-color: {_matplotlib.colors.rgb2hex(rgba)};"
+ f"color: {text_color};"
)
else:
return f"color: {mpl.colors.rgb2hex(rgba)};"
return f"color: {_matplotlib.colors.rgb2hex(rgba)};"

if data.ndim == 1:
return [css(rgba, text_only) for rgba in rgbas]
Expand Down Expand Up @@ -3885,18 +3898,20 @@ def css_calc(x, left: float, right: float, align: str, color: str | list | tuple
rgbas = None
if cmap is not None:
# use the matplotlib colormap input
with _mpl(Styler.bar) as (plt, mpl):
with _mpl(Styler.bar) as (_pyplot, _matplotlib):
cmap = (
mpl.colormaps[cmap]
_matplotlib.colormaps[cmap]
if isinstance(cmap, str)
else cmap # assumed to be a Colormap instance as documented
)
norm = mpl.colors.Normalize(left, right)
norm = _matplotlib.colors.Normalize(left, right)
rgbas = cmap(norm(values))
if data.ndim == 1:
rgbas = [mpl.colors.rgb2hex(rgba) for rgba in rgbas]
rgbas = [_matplotlib.colors.rgb2hex(rgba) for rgba in rgbas]
else:
rgbas = [[mpl.colors.rgb2hex(rgba) for rgba in row] for row in rgbas]
rgbas = [
[_matplotlib.colors.rgb2hex(rgba) for rgba in row] for row in rgbas
]

assert isinstance(align, str) # mypy: should now be in [left, right, mid, zero]
if data.ndim == 1:
Expand Down
9 changes: 6 additions & 3 deletions pandas/io/json/_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@

import numpy as np

from pandas._libs import json
from pandas._libs.json import (
dumps,
loads,
)
from pandas._libs.tslibs import iNaT
from pandas._typing import (
CompressionOptions,
Expand Down Expand Up @@ -73,8 +76,8 @@

FrameSeriesStrT = TypeVar("FrameSeriesStrT", bound=Literal["frame", "series"])

loads = json.loads
dumps = json.dumps
loads = loads
dumps = dumps


# interface to/from
Expand Down
10 changes: 5 additions & 5 deletions pandas/io/xml.py
Original file line number Diff line number Diff line change
Expand Up @@ -533,9 +533,9 @@ def _parse_doc(

with preprocess_data(handle_data) as xml_data:
curr_parser = XMLParser(encoding=self.encoding)
doc = parse(xml_data, parser=curr_parser)
document = parse(xml_data, parser=curr_parser)

return doc.getroot()
return document.getroot()


class _LxmlFrameParser(_XMLFrameParser):
Expand Down Expand Up @@ -648,13 +648,13 @@ def _parse_doc(
"Can not pass encoding None when input is StringIO."
)

doc = fromstring(
document = fromstring(
xml_data.getvalue().encode(self.encoding), parser=curr_parser
)
else:
doc = parse(xml_data, parser=curr_parser)
document = parse(xml_data, parser=curr_parser)

return doc
return document

def _transform_doc(self) -> _XSLTResultTree:
"""
Expand Down