Skip to content

Commit e71d04a

Browse files
lithomas1jreback
authored andcommitted
CLN : f-string instead of str.format() in pandas/utils and pandas/io/formats (#30250)
1 parent cc5b417 commit e71d04a

10 files changed

+75
-115
lines changed

pandas/io/formats/css.py

+6-7
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,7 @@ def expand(self, prop, value):
1818
mapping = self.SIDE_SHORTHANDS[len(tokens)]
1919
except KeyError:
2020
warnings.warn(
21-
'Could not expand "{prop}: {val}"'.format(prop=prop, val=value),
22-
CSSWarning,
21+
f'Could not expand "{prop}: {value}"', CSSWarning,
2322
)
2423
return
2524
for key, idx in zip(self.SIDES, mapping):
@@ -110,14 +109,14 @@ def __call__(self, declarations_str, inherited=None):
110109

111110
# 3. TODO: resolve other font-relative units
112111
for side in self.SIDES:
113-
prop = "border-{side}-width".format(side=side)
112+
prop = f"border-{side}-width"
114113
if prop in props:
115114
props[prop] = self.size_to_pt(
116115
props[prop], em_pt=font_size, conversions=self.BORDER_WIDTH_RATIOS
117116
)
118117
for prop in [
119-
"margin-{side}".format(side=side),
120-
"padding-{side}".format(side=side),
118+
f"margin-{side}",
119+
f"padding-{side}",
121120
]:
122121
if prop in props:
123122
# TODO: support %
@@ -206,9 +205,9 @@ def _error():
206205

207206
val = round(val, 5)
208207
if int(val) == val:
209-
size_fmt = "{fmt:d}pt".format(fmt=int(val))
208+
size_fmt = f"{int(val):d}pt"
210209
else:
211-
size_fmt = "{fmt:f}pt".format(fmt=val)
210+
size_fmt = f"{val:f}pt"
212211
return size_fmt
213212

214213
def atomize(self, declarations):

pandas/io/formats/excel.py

+9-10
Original file line numberDiff line numberDiff line change
@@ -91,6 +91,7 @@ def build_xlstyle(self, props):
9191
"font": self.build_font(props),
9292
"number_format": self.build_number_format(props),
9393
}
94+
9495
# TODO: handle cell width and height: needs support in pandas.io.excel
9596

9697
def remove_none(d):
@@ -132,12 +133,10 @@ def build_border(self, props):
132133
return {
133134
side: {
134135
"style": self._border_style(
135-
props.get("border-{side}-style".format(side=side)),
136-
props.get("border-{side}-width".format(side=side)),
137-
),
138-
"color": self.color_to_excel(
139-
props.get("border-{side}-color".format(side=side))
136+
props.get(f"border-{side}-style"),
137+
props.get(f"border-{side}-width"),
140138
),
139+
"color": self.color_to_excel(props.get(f"border-{side}-color")),
141140
}
142141
for side in ["top", "right", "bottom", "left"]
143142
}
@@ -427,7 +426,7 @@ def _format_value(self, val):
427426
if missing.isposinf_scalar(val):
428427
val = self.inf_rep
429428
elif missing.isneginf_scalar(val):
430-
val = "-{inf}".format(inf=self.inf_rep)
429+
val = f"-{self.inf_rep}"
431430
elif self.float_format is not None:
432431
val = float(self.float_format % val)
433432
if getattr(val, "tzinfo", None) is not None:
@@ -509,8 +508,8 @@ def _format_header_regular(self):
509508
if has_aliases:
510509
if len(self.header) != len(self.columns):
511510
raise ValueError(
512-
"Writing {cols} cols but got {alias} "
513-
"aliases".format(cols=len(self.columns), alias=len(self.header))
511+
f"Writing {len(self.columns)} cols but got {len(self.header)} "
512+
"aliases"
514513
)
515514
else:
516515
colnames = self.header
@@ -718,8 +717,8 @@ def write(
718717
if num_rows > self.max_rows or num_cols > self.max_cols:
719718
raise ValueError(
720719
"This sheet is too large! Your sheet size is: "
721-
+ "{}, {} ".format(num_rows, num_cols)
722-
+ "Max sheet size is: {}, {}".format(self.max_rows, self.max_cols)
720+
f"{num_rows}, {num_cols} "
721+
f"Max sheet size is: {self.max_rows}, {self.max_cols}"
723722
)
724723

725724
if isinstance(writer, ExcelWriter):

pandas/io/formats/style.py

+18-33
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@ def default_display_func(x):
165165
if self.na_rep is not None and pd.isna(x):
166166
return self.na_rep
167167
elif is_float(x):
168-
display_format = "{0:.{precision}f}".format(x, precision=self.precision)
168+
display_format = f"{x:.{self.precision}f}"
169169
return display_format
170170
else:
171171
return x
@@ -293,7 +293,7 @@ def format_attr(pair):
293293
name = self.data.columns.names[r]
294294
cs = [
295295
BLANK_CLASS if name is None else INDEX_NAME_CLASS,
296-
"level{lvl}".format(lvl=r),
296+
f"level{r}",
297297
]
298298
name = BLANK_VALUE if name is None else name
299299
row_es.append(
@@ -310,8 +310,8 @@ def format_attr(pair):
310310
for c, value in enumerate(clabels[r]):
311311
cs = [
312312
COL_HEADING_CLASS,
313-
"level{lvl}".format(lvl=r),
314-
"col{col}".format(col=c),
313+
f"level{r}",
314+
f"col{c}",
315315
]
316316
cs.extend(
317317
cell_context.get("col_headings", {}).get(r, {}).get(c, [])
@@ -339,7 +339,7 @@ def format_attr(pair):
339339
index_header_row = []
340340

341341
for c, name in enumerate(self.data.index.names):
342-
cs = [INDEX_NAME_CLASS, "level{lvl}".format(lvl=c)]
342+
cs = [INDEX_NAME_CLASS, f"level{c}"]
343343
name = "" if name is None else name
344344
index_header_row.append(
345345
{"type": "th", "value": name, "class": " ".join(cs)}
@@ -358,8 +358,8 @@ def format_attr(pair):
358358
for c, value in enumerate(rlabels[r]):
359359
rid = [
360360
ROW_HEADING_CLASS,
361-
"level{lvl}".format(lvl=c),
362-
"row{row}".format(row=r),
361+
f"level{c}",
362+
f"row{r}",
363363
]
364364
es = {
365365
"type": "th",
@@ -377,7 +377,7 @@ def format_attr(pair):
377377
row_es.append(es)
378378

379379
for c, col in enumerate(self.data.columns):
380-
cs = [DATA_CLASS, "row{row}".format(row=r), "col{col}".format(col=c)]
380+
cs = [DATA_CLASS, f"row{r}", f"col{c}"]
381381
cs.extend(cell_context.get("data", {}).get(r, {}).get(c, []))
382382
formatter = self._display_funcs[(r, c)]
383383
value = self.data.iloc[r, c]
@@ -399,12 +399,7 @@ def format_attr(pair):
399399
props.append(x.split(":"))
400400
else:
401401
props.append(["", ""])
402-
cellstyle.append(
403-
{
404-
"props": props,
405-
"selector": "row{row}_col{col}".format(row=r, col=c),
406-
}
407-
)
402+
cellstyle.append({"props": props, "selector": f"row{r}_col{c}"})
408403
body.append(row_es)
409404

410405
table_attr = self.table_attributes
@@ -971,9 +966,7 @@ def hide_columns(self, subset):
971966

972967
@staticmethod
973968
def _highlight_null(v, null_color):
974-
return (
975-
"background-color: {color}".format(color=null_color) if pd.isna(v) else ""
976-
)
969+
return f"background-color: {null_color}" if pd.isna(v) else ""
977970

978971
def highlight_null(self, null_color="red"):
979972
"""
@@ -1126,9 +1119,7 @@ def relative_luminance(rgba):
11261119
def css(rgba):
11271120
dark = relative_luminance(rgba) < text_color_threshold
11281121
text_color = "#f1f1f1" if dark else "#000000"
1129-
return "background-color: {b};color: {c};".format(
1130-
b=colors.rgb2hex(rgba), c=text_color
1131-
)
1122+
return f"background-color: {colors.rgb2hex(rgba)};color: {text_color};"
11321123

11331124
if s.ndim == 1:
11341125
return [css(rgba) for rgba in rgbas]
@@ -1160,7 +1151,7 @@ def set_properties(self, subset=None, **kwargs):
11601151
>>> df.style.set_properties(color="white", align="right")
11611152
>>> df.style.set_properties(**{'background-color': 'yellow'})
11621153
"""
1163-
values = ";".join("{p}: {v}".format(p=p, v=v) for p, v in kwargs.items())
1154+
values = ";".join(f"{p}: {v}" for p, v in kwargs.items())
11641155
f = lambda x: values
11651156
return self.applymap(f, subset=subset)
11661157

@@ -1191,12 +1182,9 @@ def css_bar(start, end, color):
11911182
if end > start:
11921183
css += "background: linear-gradient(90deg,"
11931184
if start > 0:
1194-
css += " transparent {s:.1f}%, {c} {s:.1f}%, ".format(
1195-
s=start, c=color
1196-
)
1197-
css += "{c} {e:.1f}%, transparent {e:.1f}%)".format(
1198-
e=min(end, width), c=color
1199-
)
1185+
css += f" transparent {start:.1f}%, {color} {start:.1f}%, "
1186+
e = min(end, width)
1187+
css += f"{color} {e:.1f}%, transparent {e:.1f}%)"
12001188
return css
12011189

12021190
def css(x):
@@ -1358,7 +1346,7 @@ def _highlight_extrema(data, color="yellow", max_=True):
13581346
"""
13591347
Highlight the min or max in a Series or DataFrame.
13601348
"""
1361-
attr = "background-color: {0}".format(color)
1349+
attr = f"background-color: {color}"
13621350

13631351
if max_:
13641352
extrema = data == np.nanmax(data.to_numpy())
@@ -1528,16 +1516,13 @@ def _maybe_wrap_formatter(formatter, na_rep: Optional[str]):
15281516
elif callable(formatter):
15291517
formatter_func = formatter
15301518
else:
1531-
msg = (
1532-
"Expected a template string or callable, got {formatter} "
1533-
"instead".format(formatter=formatter)
1534-
)
1519+
msg = f"Expected a template string or callable, got {formatter} instead"
15351520
raise TypeError(msg)
15361521

15371522
if na_rep is None:
15381523
return formatter_func
15391524
elif isinstance(na_rep, str):
15401525
return lambda x: na_rep if pd.isna(x) else formatter_func(x)
15411526
else:
1542-
msg = "Expected a string, got {na_rep} instead".format(na_rep=na_rep)
1527+
msg = f"Expected a string, got {na_rep} instead"
15431528
raise TypeError(msg)

pandas/util/_decorators.py

+7-12
Original file line numberDiff line numberDiff line change
@@ -84,18 +84,13 @@ def wrapper(*args, **kwargs) -> Callable[..., Any]:
8484
if empty1 or empty2 and not summary:
8585
raise AssertionError(doc_error_msg)
8686
wrapper.__doc__ = dedent(
87-
"""
88-
{summary}
89-
90-
.. deprecated:: {depr_version}
91-
{depr_msg}
92-
93-
{rest_of_docstring}"""
94-
).format(
95-
summary=summary.strip(),
96-
depr_version=version,
97-
depr_msg=msg,
98-
rest_of_docstring=dedent(doc),
87+
f"""
88+
{summary.strip()}
89+
90+
.. deprecated:: {version}
91+
{msg}
92+
93+
{dedent(doc)}"""
9994
)
10095

10196
return wrapper

pandas/util/_depr_module.py

+8-12
Original file line numberDiff line numberDiff line change
@@ -61,26 +61,24 @@ def __getattr__(self, name):
6161

6262
if self.removals is not None and name in self.removals:
6363
warnings.warn(
64-
"{deprmod}.{name} is deprecated and will be removed in "
65-
"a future version.".format(deprmod=self.deprmod, name=name),
64+
f"{self.deprmod}.{name} is deprecated and will be removed in "
65+
"a future version.",
6666
FutureWarning,
6767
stacklevel=2,
6868
)
6969
elif self.moved is not None and name in self.moved:
7070
warnings.warn(
71-
"{deprmod} is deprecated and will be removed in "
72-
"a future version.\nYou can access {name} as {moved}".format(
73-
deprmod=self.deprmod, name=name, moved=self.moved[name]
74-
),
71+
f"{self.deprmod} is deprecated and will be removed in "
72+
f"a future version.\nYou can access {name} as {self.moved[name]}",
7573
FutureWarning,
7674
stacklevel=2,
7775
)
7876
else:
7977
deprmodto = self.deprmodto
8078
if deprmodto is False:
8179
warnings.warn(
82-
"{deprmod}.{name} is deprecated and will be removed in "
83-
"a future version.".format(deprmod=self.deprmod, name=name),
80+
f"{self.deprmod}.{name} is deprecated and will be removed in "
81+
"a future version.",
8482
FutureWarning,
8583
stacklevel=2,
8684
)
@@ -89,10 +87,8 @@ def __getattr__(self, name):
8987
deprmodto = obj.__module__
9088
# The object is actually located in another module.
9189
warnings.warn(
92-
"{deprmod}.{name} is deprecated. Please use "
93-
"{deprmodto}.{name} instead.".format(
94-
deprmod=self.deprmod, name=name, deprmodto=deprmodto
95-
),
90+
f"{self.deprmod}.{name} is deprecated. Please use "
91+
f"{deprmodto}.{name} instead.",
9692
FutureWarning,
9793
stacklevel=2,
9894
)

pandas/util/_doctools.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ def _insert_index(self, data):
113113
data.insert(0, "Index", data.index)
114114
else:
115115
for i in range(idx_nlevels):
116-
data.insert(i, "Index{0}".format(i), data.index._get_level_values(i))
116+
data.insert(i, f"Index{i}", data.index._get_level_values(i))
117117

118118
col_nlevels = data.columns.nlevels
119119
if col_nlevels > 1:

pandas/util/_print_versions.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -40,14 +40,14 @@ def get_sys_info() -> List[Tuple[str, Optional[Union[str, int]]]]:
4040
[
4141
("python", ".".join(map(str, sys.version_info))),
4242
("python-bits", struct.calcsize("P") * 8),
43-
("OS", "{sysname}".format(sysname=sysname)),
44-
("OS-release", "{release}".format(release=release)),
43+
("OS", f"{sysname}"),
44+
("OS-release", f"{release}"),
4545
# ("Version", "{version}".format(version=version)),
46-
("machine", "{machine}".format(machine=machine)),
47-
("processor", "{processor}".format(processor=processor)),
48-
("byteorder", "{byteorder}".format(byteorder=sys.byteorder)),
49-
("LC_ALL", "{lc}".format(lc=os.environ.get("LC_ALL", "None"))),
50-
("LANG", "{lang}".format(lang=os.environ.get("LANG", "None"))),
46+
("machine", f"{machine}"),
47+
("processor", f"{processor}"),
48+
("byteorder", f"{sys.byteorder}"),
49+
("LC_ALL", f"{os.environ.get('LC_ALL', 'None')}"),
50+
("LANG", f"{os.environ.get('LANG', 'None')}"),
5151
("LOCALE", ".".join(map(str, locale.getlocale()))),
5252
]
5353
)

pandas/util/_test_decorators.py

+6-9
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ def skip_if_installed(package: str) -> Callable:
129129
The name of the package.
130130
"""
131131
return pytest.mark.skipif(
132-
safe_import(package), reason="Skipping because {} is installed.".format(package)
132+
safe_import(package), reason=f"Skipping because {package} is installed."
133133
)
134134

135135

@@ -163,9 +163,9 @@ def skip_if_no(package: str, min_version: Optional[str] = None) -> Callable:
163163
a pytest.mark.skipif to use as either a test decorator or a
164164
parametrization mark.
165165
"""
166-
msg = "Could not import '{}'".format(package)
166+
msg = f"Could not import '{package}'"
167167
if min_version:
168-
msg += " satisfying a min_version of {}".format(min_version)
168+
msg += f" satisfying a min_version of {min_version}"
169169
return pytest.mark.skipif(
170170
not safe_import(package, min_version=min_version), reason=msg
171171
)
@@ -181,20 +181,17 @@ def skip_if_no(package: str, min_version: Optional[str] = None) -> Callable:
181181
is_platform_windows(), reason="not used on win32"
182182
)
183183
skip_if_has_locale = pytest.mark.skipif(
184-
_skip_if_has_locale(),
185-
reason="Specific locale is set {lang}".format(lang=locale.getlocale()[0]),
184+
_skip_if_has_locale(), reason=f"Specific locale is set {locale.getlocale()[0]}",
186185
)
187186
skip_if_not_us_locale = pytest.mark.skipif(
188-
_skip_if_not_us_locale(),
189-
reason="Specific locale is set {lang}".format(lang=locale.getlocale()[0]),
187+
_skip_if_not_us_locale(), reason=f"Specific locale is set {locale.getlocale()[0]}",
190188
)
191189
skip_if_no_scipy = pytest.mark.skipif(
192190
_skip_if_no_scipy(), reason="Missing SciPy requirement"
193191
)
194192
skip_if_no_ne = pytest.mark.skipif(
195193
not _USE_NUMEXPR,
196-
reason="numexpr enabled->{enabled}, "
197-
"installed->{installed}".format(enabled=_USE_NUMEXPR, installed=_NUMEXPR_INSTALLED),
194+
reason=f"numexpr enabled->{_USE_NUMEXPR}, " f"installed->{_NUMEXPR_INSTALLED}",
198195
)
199196

200197

pandas/util/_tester.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ def test(extra_args=None):
2222
extra_args = [extra_args]
2323
cmd = extra_args
2424
cmd += [PKG]
25-
print("running: pytest {}".format(" ".join(cmd)))
25+
print(f"running: pytest {' '.join(cmd)}")
2626
sys.exit(pytest.main(cmd))
2727

2828

0 commit comments

Comments
 (0)