Skip to content

Commit ea3c120

Browse files
committed
CLN: apply manual f-string fixes inspired by flynt -tc
1 parent 9108900 commit ea3c120

36 files changed

+92
-99
lines changed

asv_bench/benchmarks/categoricals.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ def setup(self):
8989
)
9090

9191
for col in ("int", "float", "timestamp"):
92-
self.df[col + "_as_str"] = self.df[col].astype(str)
92+
self.df[f"{col}_as_str"] = self.df[col].astype(str)
9393

9494
for col in self.df.columns:
9595
self.df[col] = self.df[col].astype("category")

asv_bench/benchmarks/frame_methods.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ def setup(self):
125125
self.df = DataFrame(np.random.randn(N * 10, N))
126126
self.df2 = DataFrame(np.random.randn(N * 50, 10))
127127
self.df3 = DataFrame(
128-
np.random.randn(N, 5 * N), columns=["C" + str(c) for c in range(N * 5)]
128+
np.random.randn(N, 5 * N), columns=[f"C{c}" for c in range(N * 5)]
129129
)
130130
self.df4 = DataFrame(np.random.randn(N * 1000, 10))
131131

asv_bench/benchmarks/inference.py

+9-8
Original file line numberDiff line numberDiff line change
@@ -166,14 +166,15 @@ def time_unique_date_strings(self, cache, count):
166166

167167

168168
class ToDatetimeISO8601:
169+
sep_format = "%Y-%m-%d %H:%M:%S"
170+
nosep_format = "%Y%m%d %H:%M:%S"
171+
169172
def setup(self):
170173
rng = date_range(start="1/1/2000", periods=20000, freq="H")
171-
self.strings = rng.strftime("%Y-%m-%d %H:%M:%S").tolist()
172-
self.strings_nosep = rng.strftime("%Y%m%d %H:%M:%S").tolist()
173-
self.strings_tz_space = [
174-
x.strftime("%Y-%m-%d %H:%M:%S") + " -0800" for x in rng
175-
]
176-
self.strings_zero_tz = [x.strftime("%Y-%m-%d %H:%M:%S") + "Z" for x in rng]
174+
self.strings = rng.strftime(self.sep_format).tolist()
175+
self.strings_nosep = rng.strftime(self.nosep_format).tolist()
176+
self.strings_tz_space = [f"{x.strftime(self.sep_format)} -0800" for x in rng]
177+
self.strings_zero_tz = [f"{x.strftime(self.sep_format)}Z" for x in rng]
177178

178179
def time_iso8601(self):
179180
to_datetime(self.strings)
@@ -182,10 +183,10 @@ def time_iso8601_nosep(self):
182183
to_datetime(self.strings_nosep)
183184

184185
def time_iso8601_format(self):
185-
to_datetime(self.strings, format="%Y-%m-%d %H:%M:%S")
186+
to_datetime(self.strings, format=self.sep_format)
186187

187188
def time_iso8601_format_no_sep(self):
188-
to_datetime(self.strings_nosep, format="%Y%m%d %H:%M:%S")
189+
to_datetime(self.strings_nosep, format=self.nosep_format)
189190

190191
def time_iso8601_tz_spaceformat(self):
191192
to_datetime(self.strings_tz_space)

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
@@ -1770,7 +1770,7 @@ def spmatrix(request):
17701770
"""
17711771
from scipy import sparse
17721772

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

17751775

17761776
@pytest.fixture(

pandas/core/arrays/categorical.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1890,7 +1890,7 @@ def _repr_categories_info(self) -> str:
18901890
start = True
18911891
cur_col_len = len(levheader) # header
18921892
sep_len, sep = (3, " < ") if self.ordered else (2, ", ")
1893-
linesep = sep.rstrip() + "\n" # remove whitespace
1893+
linesep = f"{sep.rstrip()}\n" # remove whitespace
18941894
for val in category_strs:
18951895
if max_width != 0 and cur_col_len + sep_len + len(val) > max_width:
18961896
levstring += linesep + (" " * (len(levheader) + 1))
@@ -1901,7 +1901,7 @@ def _repr_categories_info(self) -> str:
19011901
levstring += val
19021902
start = False
19031903
# replace to simple save space by
1904-
return levheader + "[" + levstring.replace(" < ... < ", " ... ") + "]"
1904+
return f"{levheader}[{levstring.replace(' < ... < ', ' ... ')}]"
19051905

19061906
def _repr_footer(self) -> str:
19071907
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
@@ -802,7 +802,7 @@ def __hash__(self) -> int:
802802
def __eq__(self, other: Any) -> bool:
803803
if isinstance(other, str):
804804
if other.startswith("M8["):
805-
other = "datetime64[" + other[3:]
805+
other = f"datetime64[{other[3:]}"
806806
return other == self.name
807807

808808
return (

pandas/core/frame.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -1095,7 +1095,7 @@ def _repr_html_(self) -> str | None:
10951095
# need to escape the <class>, should be the first line.
10961096
val = buf.getvalue().replace("<", r"&lt;", 1)
10971097
val = val.replace(">", r"&gt;", 1)
1098-
return "<pre>" + val + "</pre>"
1098+
return f"<pre>{val}</pre>"
10991099

11001100
if get_option("display.notebook_repr_html"):
11011101
max_rows = get_option("display.max_rows")
@@ -8945,8 +8945,7 @@ def explode(
89458945
if not self.columns.is_unique:
89468946
duplicate_cols = self.columns[self.columns.duplicated()].tolist()
89478947
raise ValueError(
8948-
"DataFrame columns must be unique. "
8949-
+ f"Duplicate columns: {duplicate_cols}"
8948+
f"DataFrame columns must be unique. Duplicate columns: {duplicate_cols}"
89508949
)
89518950

89528951
columns: list[Hashable]

pandas/core/groupby/groupby.py

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

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

15401540
else:
15411541
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
@@ -845,7 +845,7 @@ def _format_native_types(
845845
def _format_data(self, name=None) -> str:
846846
# TODO: integrate with categorical and make generic
847847
# name argument is unused here; just for compat with base / categorical
848-
return self._data._format_data() + "," + self._format_space()
848+
return f"{self._data._format_data()},{self._format_space()}"
849849

850850
# --------------------------------------------------------------------
851851
# 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

+2-2
Original file line numberDiff line numberDiff line change
@@ -194,11 +194,11 @@ class CSSResolver:
194194

195195
CSS_EXPANSIONS = {
196196
**{
197-
"-".join(["border", prop] if prop else ["border"]): _border_expander(prop)
197+
(f"border-{prop}" if prop else "border"): _border_expander(prop)
198198
for prop in ["", "top", "right", "bottom", "left"]
199199
},
200200
**{
201-
"-".join(["border", prop]): _side_expander("border-{:s}-" + prop)
201+
f"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

0 commit comments

Comments
 (0)