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

57 changes: 34 additions & 23 deletions pandas/io/formats/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,43 +72,44 @@
from matplotlib.colors import Colormap

try:
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib as mpls
import matplotlib.pyplot as plts

has_mpl = True
except ImportError:
has_mpl = False
no_mpl_message = "{0} requires matplotlib."


@contextmanager
def _mpl(func: Callable) -> Generator[tuple[Any, Any], None, None]:
if has_mpl:
yield plt, mpl
yield plts, mpls
else:
raise ImportError(f"{func.__name__} requires matplotlib.")
raise ImportError(no_mpl_message.format(func.__name__))


####
# 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 +1187,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 +1346,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 +1691,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 +1930,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 +2686,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 +2869,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 +2901,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 +3024,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 +3069,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 +3115,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 +3161,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 +3267,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,7 +3608,7 @@ 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 (_, mpl):
smin = np.nanmin(gmap) if vmin is None else vmin
smax = np.nanmax(gmap) if vmax is None else vmax
rng = smax - smin
Expand Down Expand Up @@ -3885,7 +3896,7 @@ 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 (_, mpl):
cmap = (
mpl.colormaps[cmap]
if isinstance(cmap, str)
Expand Down
22 changes: 11 additions & 11 deletions pandas/io/json/_json.py
Original file line number Diff line number Diff line change
Expand Up @@ -912,7 +912,7 @@ def read(self) -> DataFrame | Series:
self.close()
return obj

def _get_object_parser(self, json) -> DataFrame | Series:
def _get_object_parser(self, json_file) -> DataFrame | Series:
"""
Parses a json document into a pandas object.
"""
Expand All @@ -929,12 +929,12 @@ def _get_object_parser(self, json) -> DataFrame | Series:
}
obj = None
if typ == "frame":
obj = FrameParser(json, **kwargs).parse()
obj = FrameParser(json_file, **kwargs).parse()

if typ == "series" or obj is None:
if not isinstance(dtype, bool):
kwargs["dtype"] = dtype
obj = SeriesParser(json, **kwargs).parse()
obj = SeriesParser(json_file, **kwargs).parse()

return obj

Expand Down Expand Up @@ -1009,7 +1009,7 @@ class Parser:

def __init__(
self,
json,
json_file,
orient,
dtype: DtypeArg | None = None,
convert_axes: bool = True,
Expand All @@ -1018,7 +1018,7 @@ def __init__(
precise_float: bool = False,
date_unit=None,
) -> None:
self.json = json
self.json_file = json_file

if orient is None:
orient = self._default_orient
Expand Down Expand Up @@ -1239,31 +1239,31 @@ class FrameParser(Parser):

def _parse(self) -> None:

json = self.json
json_file = self.json_file
orient = self.orient

if orient == "columns":
self.obj = DataFrame(
loads(json, precise_float=self.precise_float), dtype=None
loads(json_file, precise_float=self.precise_float), dtype=None
)
elif orient == "split":
decoded = {
str(k): v
for k, v in loads(json, precise_float=self.precise_float).items()
for k, v in loads(json_file, precise_float=self.precise_float).items()
}
self.check_keys_split(decoded)
self.obj = DataFrame(dtype=None, **decoded)
elif orient == "index":
self.obj = DataFrame.from_dict(
loads(json, precise_float=self.precise_float),
loads(json_file, precise_float=self.precise_float),
dtype=None,
orient="index",
)
elif orient == "table":
self.obj = parse_table_schema(json, precise_float=self.precise_float)
self.obj = parse_table_schema(json_file, precise_float=self.precise_float)
else:
self.obj = DataFrame(
loads(json, precise_float=self.precise_float), dtype=None
loads(json_file, precise_float=self.precise_float), dtype=None
)

def _process_converter(self, f, filt=None) -> None:
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