Skip to content

Commit 457c422

Browse files
committed
CLN: use f-strings where possible
Mechanically transformed with `flynt -tc -a -v`
1 parent edbac36 commit 457c422

File tree

110 files changed

+334
-342
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

110 files changed

+334
-342
lines changed

pandas/_config/config.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -499,7 +499,7 @@ def register_option(
499499
path = key.split(".")
500500

501501
for k in path:
502-
if not re.match("^" + tokenize.Name + "$", k):
502+
if not re.match(f"^{tokenize.Name}$", k):
503503
raise ValueError(f"{k} is not a valid identifier")
504504
if keyword.iskeyword(k):
505505
raise ValueError(f"{k} is a python keyword")
@@ -707,7 +707,7 @@ def pp_options_list(keys: Iterable[str], width: int = 80, _print: bool = False):
707707
from textwrap import wrap
708708

709709
def pp(name: str, ks: Iterable[str]) -> list[str]:
710-
pfx = "- " + name + ".[" if name else ""
710+
pfx = f"- {name}.[" if name else ""
711711
ls = wrap(
712712
", ".join(ks),
713713
width,
@@ -716,7 +716,7 @@ def pp(name: str, ks: Iterable[str]) -> list[str]:
716716
break_long_words=False,
717717
)
718718
if ls and ls[-1] and name:
719-
ls[-1] = ls[-1] + "]"
719+
ls[-1] = f"{ls[-1]}]"
720720
return ls
721721

722722
ls: list[str] = []

pandas/conftest.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1773,7 +1773,7 @@ def spmatrix(request):
17731773
"""
17741774
from scipy import sparse
17751775

1776-
return getattr(sparse, request.param + "_matrix")
1776+
return getattr(sparse, f"{request.param}_matrix")
17771777

17781778

17791779
@pytest.fixture(

pandas/core/arraylike.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -304,8 +304,7 @@ def array_ufunc(self, ufunc: np.ufunc, method: str, *inputs: Any, **kwargs: Any)
304304
# well. Previously this raised an internal ValueError. We might
305305
# support it someday, so raise a NotImplementedError.
306306
raise NotImplementedError(
307-
"Cannot apply ufunc {} to mixed DataFrame and Series "
308-
"inputs.".format(ufunc)
307+
f"Cannot apply ufunc {ufunc} to mixed DataFrame and Series inputs."
309308
)
310309
axes = self.axes
311310
for obj in alignable[1:]:

pandas/core/arrays/categorical.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -2166,7 +2166,7 @@ def _repr_categories_info(self) -> str:
21662166
start = True
21672167
cur_col_len = len(levheader) # header
21682168
sep_len, sep = (3, " < ") if self.ordered else (2, ", ")
2169-
linesep = sep.rstrip() + "\n" # remove whitespace
2169+
linesep = f"{sep.rstrip()}\n" # remove whitespace
21702170
for val in category_strs:
21712171
if max_width != 0 and cur_col_len + sep_len + len(val) > max_width:
21722172
levstring += linesep + (" " * (len(levheader) + 1))
@@ -2177,7 +2177,7 @@ def _repr_categories_info(self) -> str:
21772177
levstring += val
21782178
start = False
21792179
# replace to simple save space by
2180-
return levheader + "[" + levstring.replace(" < ... < ", " ... ") + "]"
2180+
return f"{levheader}[{levstring.replace(' < ... < ', ' ... ')}]"
21812181

21822182
def _repr_footer(self) -> str:
21832183
info = self._repr_categories_info()

pandas/core/arrays/masked.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1058,7 +1058,7 @@ def _reduce(self, name: str, *, skipna: bool = True, **kwargs):
10581058
data = self.to_numpy("float64", na_value=np.nan)
10591059

10601060
# median, var, std, skew, kurt, idxmin, idxmax
1061-
op = getattr(nanops, "nan" + name)
1061+
op = getattr(nanops, f"nan{name}")
10621062
result = op(data, axis=0, skipna=skipna, mask=mask, **kwargs)
10631063

10641064
if np.isnan(result):

pandas/core/arrays/string_arrow.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -317,11 +317,11 @@ def _str_contains(
317317
return result
318318

319319
def _str_startswith(self, pat: str, na=None):
320-
pat = "^" + re.escape(pat)
320+
pat = f"^{re.escape(pat)}"
321321
return self._str_contains(pat, na=na, regex=True)
322322

323323
def _str_endswith(self, pat: str, na=None):
324-
pat = re.escape(pat) + "$"
324+
pat = f"{re.escape(pat)}$"
325325
return self._str_contains(pat, na=na, regex=True)
326326

327327
def _str_replace(
@@ -345,14 +345,14 @@ def _str_match(
345345
self, pat: str, case: bool = True, flags: int = 0, na: Scalar | None = None
346346
):
347347
if not pat.startswith("^"):
348-
pat = "^" + pat
348+
pat = f"^{pat}"
349349
return self._str_contains(pat, case, flags, na, regex=True)
350350

351351
def _str_fullmatch(
352352
self, pat, case: bool = True, flags: int = 0, na: Scalar | None = None
353353
):
354354
if not pat.endswith("$") or pat.endswith("//$"):
355-
pat = pat + "$"
355+
pat = f"{pat}$"
356356
return self._str_match(pat, case, flags, na)
357357

358358
def _str_isalnum(self):

pandas/core/computation/expr.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -410,7 +410,7 @@ def visit(self, node, **kwargs):
410410
e.msg = "Python keyword not valid identifier in numexpr query"
411411
raise e
412412

413-
method = "visit_" + type(node).__name__
413+
method = f"visit_{type(node).__name__}"
414414
visitor = getattr(self, method)
415415
return visitor(node, **kwargs)
416416

pandas/core/computation/parsing.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ def create_valid_python_identifier(name: str) -> str:
5959
)
6060

6161
name = "".join([special_characters_replacements.get(char, char) for char in name])
62-
name = "BACKTICK_QUOTED_STRING_" + name
62+
name = f"BACKTICK_QUOTED_STRING_{name}"
6363

6464
if not name.isidentifier():
6565
raise SyntaxError(f"Could not convert '{name}' to a valid Python identifier.")

pandas/core/computation/scope.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -250,7 +250,7 @@ def _get_vars(self, stack, scopes: list[str]) -> None:
250250
variables = itertools.product(scopes, stack)
251251
for scope, (frame, _, _, _, _, _) in variables:
252252
try:
253-
d = getattr(frame, "f_" + scope)
253+
d = getattr(frame, f"f_{scope}")
254254
self.scope = DeepChainMap(self.scope.new_child(d))
255255
finally:
256256
# won't remove it, but DECREF it

pandas/core/dtypes/dtypes.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -804,7 +804,7 @@ def __hash__(self) -> int:
804804
def __eq__(self, other: Any) -> bool:
805805
if isinstance(other, str):
806806
if other.startswith("M8["):
807-
other = "datetime64[" + other[3:]
807+
other = f"datetime64[{other[3:]}"
808808
return other == self.name
809809

810810
return (

pandas/core/frame.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1078,7 +1078,7 @@ def _repr_html_(self) -> str | None:
10781078
# need to escape the <class>, should be the first line.
10791079
val = buf.getvalue().replace("<", r"&lt;", 1)
10801080
val = val.replace(">", r"&gt;", 1)
1081-
return "<pre>" + val + "</pre>"
1081+
return f"<pre>{val}</pre>"
10821082

10831083
if get_option("display.notebook_repr_html"):
10841084
max_rows = get_option("display.max_rows")

pandas/core/groupby/groupby.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1531,9 +1531,9 @@ def f(g):
15311531
with np.errstate(all="ignore"):
15321532
return func(g, *args, **kwargs)
15331533

1534-
elif hasattr(nanops, "nan" + func):
1534+
elif hasattr(nanops, f"nan{func}"):
15351535
# TODO: should we wrap this in to e.g. _is_builtin_func?
1536-
f = getattr(nanops, "nan" + func)
1536+
f = getattr(nanops, f"nan{func}")
15371537

15381538
else:
15391539
raise ValueError(

pandas/core/indexes/category.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -349,7 +349,7 @@ def _format_attrs(self):
349349
attrs = [
350350
(
351351
"categories",
352-
"[" + ", ".join(self._data._repr_categories()) + "]",
352+
f"[{', '.join(self._data._repr_categories())}]",
353353
),
354354
("ordered", self.ordered),
355355
]

pandas/core/indexes/interval.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -831,7 +831,7 @@ def _format_native_types(
831831
def _format_data(self, name=None) -> str:
832832
# TODO: integrate with categorical and make generic
833833
# name argument is unused here; just for compat with base / categorical
834-
return self._data._format_data() + "," + self._format_space()
834+
return f"{self._data._format_data()},{self._format_space()}"
835835

836836
# --------------------------------------------------------------------
837837
# Set Operations

pandas/core/interchange/column.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -329,7 +329,7 @@ def _get_validity_buffer(self) -> tuple[PandasBuffer, Any]:
329329
return buffer, dtype
330330

331331
try:
332-
msg = _NO_VALIDITY_BUFFER[null] + " so does not have a separate mask"
332+
msg = f"{_NO_VALIDITY_BUFFER[null]} so does not have a separate mask"
333333
except KeyError:
334334
# TODO: implement for other bit/byte masks?
335335
raise NotImplementedError("See self.describe_null")

pandas/core/nanops.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1043,7 +1043,7 @@ def nansem(
10431043

10441044

10451045
def _nanminmax(meth, fill_value_typ):
1046-
@bottleneck_switch(name="nan" + meth)
1046+
@bottleneck_switch(name=f"nan{meth}")
10471047
@_datetimelike_compat
10481048
def reduction(
10491049
values: np.ndarray,

pandas/core/ops/docstrings.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,11 @@ def make_flex_doc(op_name: str, typ: str) -> str:
2525
op_desc_op = op_desc["op"]
2626
assert op_desc_op is not None # for mypy
2727
if op_name.startswith("r"):
28-
equiv = "other " + op_desc_op + " " + typ
28+
equiv = f"other {op_desc_op} {typ}"
2929
elif op_name == "divmod":
3030
equiv = f"{op_name}({typ}, other)"
3131
else:
32-
equiv = typ + " " + op_desc_op + " other"
32+
equiv = f"{typ} {op_desc_op} other"
3333

3434
if typ == "series":
3535
base_doc = _flex_doc_SERIES

pandas/io/clipboard/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -312,7 +312,7 @@ def __init__(self, f) -> None:
312312
def __call__(self, *args):
313313
ret = self.f(*args)
314314
if not ret and get_errno():
315-
raise PyperclipWindowsException("Error calling " + self.f.__name__)
315+
raise PyperclipWindowsException(f"Error calling {self.f.__name__}")
316316
return ret
317317

318318
def __setattr__(self, key, value):

pandas/io/formats/css.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,7 @@ class CSSResolver:
198198
for prop in ["", "top", "right", "bottom", "left"]
199199
},
200200
**{
201-
"-".join(["border", prop]): _side_expander("border-{:s}-" + prop)
201+
"-".join(["border", prop]): _side_expander(f"border-{{:s}}-{prop}")
202202
for prop in ["color", "style", "width"]
203203
},
204204
**{

pandas/io/formats/format.py

+10-10
Original file line numberDiff line numberDiff line change
@@ -256,7 +256,7 @@ def to_string(self) -> str:
256256

257257
fmt_values = [i.strip() for i in fmt_values]
258258
values = ", ".join(fmt_values)
259-
result = ["[" + values + "]"]
259+
result = [f"[{values}]"]
260260
if self.footer:
261261
footer = self._get_footer()
262262
if footer:
@@ -417,10 +417,10 @@ def to_string(self) -> str:
417417
result = self.adj.adjoin(3, fmt_values)
418418

419419
if self.header and have_header:
420-
result = fmt_index[0] + "\n" + result
420+
result = f"{fmt_index[0]}\n{result}"
421421

422422
if footer:
423-
result += "\n" + footer
423+
result += f"\n{footer}"
424424

425425
return str("".join(result))
426426

@@ -936,7 +936,7 @@ def space_format(x, y):
936936
and need_leadsp[x]
937937
and not restrict_formatting
938938
):
939-
return " " + y
939+
return f" {y}"
940940
return y
941941

942942
str_columns = list(
@@ -951,7 +951,7 @@ def space_format(x, y):
951951
dtypes = self.frame.dtypes
952952
need_leadsp = dict(zip(fmt_columns, map(is_numeric_dtype, dtypes)))
953953
str_columns = [
954-
[" " + x if not self._get_formatter(i) and need_leadsp[x] else x]
954+
[f" {x}" if not self._get_formatter(i) and need_leadsp[x] else x]
955955
for i, x in enumerate(fmt_columns)
956956
]
957957
# self.str_columns = str_columns
@@ -1534,7 +1534,7 @@ def format_values_with(float_format):
15341534
# default formatter leaves a space to the left when formatting
15351535
# floats, must be consistent for left-justifying NaNs (GH #25061)
15361536
if self.justify == "left":
1537-
na_rep = " " + self.na_rep
1537+
na_rep = f" {self.na_rep}"
15381538
else:
15391539
na_rep = self.na_rep
15401540

@@ -1726,7 +1726,7 @@ def format_percentiles(
17261726

17271727
if np.all(int_idx):
17281728
out = percentiles_round_type.astype(str)
1729-
return [i + "%" for i in out]
1729+
return [f"{i}%" for i in out]
17301730

17311731
unique_pcts = np.unique(percentiles)
17321732
to_begin = unique_pcts[0] if unique_pcts[0] > 0 else None
@@ -1741,7 +1741,7 @@ def format_percentiles(
17411741
out[int_idx] = percentiles[int_idx].round().astype(int).astype(str)
17421742

17431743
out[~int_idx] = percentiles[~int_idx].round(prec).astype(str)
1744-
return [i + "%" for i in out]
1744+
return [f"{i}%" for i in out]
17451745

17461746

17471747
def is_dates_only(values: np.ndarray | DatetimeArray | Index | DatetimeIndex) -> bool:
@@ -1929,7 +1929,7 @@ def _make_fixed_width(
19291929
def just(x: str) -> str:
19301930
if conf_max is not None:
19311931
if (conf_max > 3) & (adjustment.len(x) > max_len):
1932-
x = x[: max_len - 3] + "..."
1932+
x = f"{x[:max_len - 3]}..."
19331933
return x
19341934

19351935
strings = [just(x) for x in strings]
@@ -2004,7 +2004,7 @@ def should_trim(values: np.ndarray | list[str]) -> bool:
20042004

20052005
# leave one 0 after the decimal points if need be.
20062006
result = [
2007-
x + "0" if is_number_with_decimal(x) and x.endswith(decimal) else x
2007+
f"{x}0" if is_number_with_decimal(x) and x.endswith(decimal) else x
20082008
for x in trimmed
20092009
]
20102010
return result

pandas/io/formats/printing.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -156,7 +156,7 @@ def _pprint_dict(
156156
)
157157

158158
if nitems < len(seq):
159-
return fmt.format(things=", ".join(pairs) + ", ...")
159+
return fmt.format(things=f"{', '.join(pairs)}, ...")
160160
else:
161161
return fmt.format(things=", ".join(pairs))
162162

@@ -339,7 +339,7 @@ def format_object_summary(
339339
if line_break_each_value:
340340
# If we want to vertically align on each value of obj, we need to
341341
# separate values by a line break and indent the values
342-
sep = ",\n " + " " * len(name)
342+
sep = f",\n {' ' * len(name)}"
343343
else:
344344
sep = ","
345345
max_seq_items = get_option("display.max_seq_items") or n
@@ -427,16 +427,16 @@ def best_len(values: list[str]) -> int:
427427
line = space2
428428

429429
for head_value in head:
430-
word = head_value + sep + " "
430+
word = f"{head_value + sep} "
431431
summary, line = _extend_line(summary, line, word, display_width, space2)
432432

433433
if is_truncated:
434434
# remove trailing space of last line
435-
summary += line.rstrip() + space2 + "..."
435+
summary += f"{line.rstrip() + space2}..."
436436
line = space2
437437

438438
for tail_item in tail[:-1]:
439-
word = tail_item + sep + " "
439+
word = f"{tail_item + sep} "
440440
summary, line = _extend_line(summary, line, word, display_width, space2)
441441

442442
# last value: no sep added + 1 space of width used for trailing ','
@@ -445,7 +445,7 @@ def best_len(values: list[str]) -> int:
445445

446446
# right now close is either '' or ', '
447447
# Now we want to include the ']', but not the maybe space.
448-
close = "]" + close.rstrip(" ")
448+
close = f"]{close.rstrip(' ')}"
449449
summary += close
450450

451451
if len(summary) > (display_width) or line_break_each_value:
@@ -454,7 +454,7 @@ def best_len(values: list[str]) -> int:
454454
summary += " "
455455

456456
# remove initial space
457-
summary = "[" + summary[len(space2) :]
457+
summary = f"[{summary[len(space2):]}"
458458

459459
return summary
460460

0 commit comments

Comments
 (0)