Skip to content

Commit 3f71b1d

Browse files
committed
CLN: use f-strings where possible
Mechanically transformed with `flynt`
1 parent 890d097 commit 3f71b1d

File tree

111 files changed

+358
-368
lines changed

Some content is hidden

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

111 files changed

+358
-368
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/_version.py

+22-22
Original file line numberDiff line numberDiff line change
@@ -88,7 +88,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=
8888
if e.errno == errno.ENOENT:
8989
continue
9090
if verbose:
91-
print("unable to run %s" % dispcmd)
91+
print(f"unable to run {dispcmd}")
9292
print(e)
9393
return None, None
9494
else:
@@ -98,8 +98,8 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False, env=
9898
stdout = p.communicate()[0].strip().decode()
9999
if p.returncode != 0:
100100
if verbose:
101-
print("unable to run %s (error)" % dispcmd)
102-
print("stdout was %s" % stdout)
101+
print(f"unable to run {dispcmd} (error)")
102+
print(f"stdout was {stdout}")
103103
return None, p.returncode
104104
return stdout, p.returncode
105105

@@ -202,15 +202,15 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
202202
# "stabilization", as well as "HEAD" and "main".
203203
tags = {r for r in refs if re.search(r"\d", r)}
204204
if verbose:
205-
print("discarding '%s', no digits" % ",".join(refs - tags))
205+
print(f"discarding '{','.join(refs - tags)}', no digits")
206206
if verbose:
207-
print("likely tags: %s" % ",".join(sorted(tags)))
207+
print(f"likely tags: {','.join(sorted(tags))}")
208208
for ref in sorted(tags):
209209
# sorting will prefer e.g. "2.0" over "2.0rc1"
210210
if ref.startswith(tag_prefix):
211211
r = ref[len(tag_prefix) :]
212212
if verbose:
213-
print("picking %s" % r)
213+
print(f"picking {r}")
214214
return {
215215
"version": r,
216216
"full-revisionid": keywords["full"].strip(),
@@ -245,7 +245,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
245245
out, rc = run_command(GITS, ["rev-parse", "--git-dir"], cwd=root, hide_stderr=True)
246246
if rc != 0:
247247
if verbose:
248-
print("Directory %s not under git control" % root)
248+
print(f"Directory {root} not under git control")
249249
raise NotThisMethod("'git rev-parse --git-dir' returned error")
250250

251251
# if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
@@ -259,7 +259,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
259259
"--always",
260260
"--long",
261261
"--match",
262-
"%s*" % tag_prefix,
262+
f"{tag_prefix}*",
263263
],
264264
cwd=root,
265265
)
@@ -294,7 +294,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
294294
mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe)
295295
if not mo:
296296
# unparsable. Maybe git-describe is misbehaving?
297-
pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out
297+
pieces["error"] = f"unable to parse git-describe output: '{describe_out}'"
298298
return pieces
299299

300300
# tag
@@ -354,12 +354,12 @@ def render_pep440(pieces):
354354
rendered = pieces["closest-tag"]
355355
if pieces["distance"] or pieces["dirty"]:
356356
rendered += plus_or_dot(pieces)
357-
rendered += "%d.g%s" % (pieces["distance"], pieces["short"])
357+
rendered += f"{int(pieces['distance'])}.g{pieces['short']}"
358358
if pieces["dirty"]:
359359
rendered += ".dirty"
360360
else:
361361
# exception #1
362-
rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"])
362+
rendered = f"0+untagged.{int(pieces['distance'])}.g{pieces['short']}"
363363
if pieces["dirty"]:
364364
rendered += ".dirty"
365365
return rendered
@@ -374,10 +374,10 @@ def render_pep440_pre(pieces):
374374
if pieces["closest-tag"]:
375375
rendered = pieces["closest-tag"]
376376
if pieces["distance"]:
377-
rendered += ".post0.dev%d" % pieces["distance"]
377+
rendered += f".post0.dev{int(pieces['distance'])}"
378378
else:
379379
# exception #1
380-
rendered = "0.post0.dev%d" % pieces["distance"]
380+
rendered = f"0.post0.dev{int(pieces['distance'])}"
381381
return rendered
382382

383383

@@ -394,17 +394,17 @@ def render_pep440_post(pieces):
394394
if pieces["closest-tag"]:
395395
rendered = pieces["closest-tag"]
396396
if pieces["distance"] or pieces["dirty"]:
397-
rendered += ".post%d" % pieces["distance"]
397+
rendered += f".post{int(pieces['distance'])}"
398398
if pieces["dirty"]:
399399
rendered += ".dev0"
400400
rendered += plus_or_dot(pieces)
401-
rendered += "g%s" % pieces["short"]
401+
rendered += f"g{pieces['short']}"
402402
else:
403403
# exception #1
404-
rendered = "0.post%d" % pieces["distance"]
404+
rendered = f"0.post{int(pieces['distance'])}"
405405
if pieces["dirty"]:
406406
rendered += ".dev0"
407-
rendered += "+g%s" % pieces["short"]
407+
rendered += f"+g{pieces['short']}"
408408
return rendered
409409

410410

@@ -419,12 +419,12 @@ def render_pep440_old(pieces):
419419
if pieces["closest-tag"]:
420420
rendered = pieces["closest-tag"]
421421
if pieces["distance"] or pieces["dirty"]:
422-
rendered += ".post%d" % pieces["distance"]
422+
rendered += f".post{int(pieces['distance'])}"
423423
if pieces["dirty"]:
424424
rendered += ".dev0"
425425
else:
426426
# exception #1
427-
rendered = "0.post%d" % pieces["distance"]
427+
rendered = f"0.post{int(pieces['distance'])}"
428428
if pieces["dirty"]:
429429
rendered += ".dev0"
430430
return rendered
@@ -441,7 +441,7 @@ def render_git_describe(pieces):
441441
if pieces["closest-tag"]:
442442
rendered = pieces["closest-tag"]
443443
if pieces["distance"]:
444-
rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
444+
rendered += f"-{int(pieces['distance'])}-g{pieces['short']}"
445445
else:
446446
# exception #1
447447
rendered = pieces["short"]
@@ -461,7 +461,7 @@ def render_git_describe_long(pieces):
461461
"""
462462
if pieces["closest-tag"]:
463463
rendered = pieces["closest-tag"]
464-
rendered += "-%d-g%s" % (pieces["distance"], pieces["short"])
464+
rendered += f"-{int(pieces['distance'])}-g{pieces['short']}"
465465
else:
466466
# exception #1
467467
rendered = pieces["short"]
@@ -497,7 +497,7 @@ def render(pieces, style):
497497
elif style == "git-describe-long":
498498
rendered = render_git_describe_long(pieces)
499499
else:
500-
raise ValueError("unknown style '%s'" % style)
500+
raise ValueError(f"unknown style '{style}'")
501501

502502
return {
503503
"version": rendered,

pandas/conftest.py

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

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

17791779

17801780
@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
@@ -2195,7 +2195,7 @@ def _repr_categories_info(self) -> str:
21952195
start = True
21962196
cur_col_len = len(levheader) # header
21972197
sep_len, sep = (3, " < ") if self.ordered else (2, ", ")
2198-
linesep = sep.rstrip() + "\n" # remove whitespace
2198+
linesep = f"{sep.rstrip()}\n" # remove whitespace
21992199
for val in category_strs:
22002200
if max_width != 0 and cur_col_len + sep_len + len(val) > max_width:
22012201
levstring += linesep + (" " * (len(levheader) + 1))
@@ -2206,7 +2206,7 @@ def _repr_categories_info(self) -> str:
22062206
levstring += val
22072207
start = False
22082208
# replace to simple save space by
2209-
return levheader + "[" + levstring.replace(" < ... < ", " ... ") + "]"
2209+
return f"{levheader}[{levstring.replace(' < ... < ', ' ... ')}]"
22102210

22112211
def _repr_footer(self) -> str:
22122212
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
@@ -350,7 +350,7 @@ def _format_attrs(self):
350350
attrs = [
351351
(
352352
"categories",
353-
"[" + ", ".join(self._data._repr_categories()) + "]",
353+
f"[{', '.join(self._data._repr_categories())}]",
354354
),
355355
("ordered", self.ordered),
356356
]

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
**{

0 commit comments

Comments
 (0)