Skip to content

Commit d270538

Browse files
akxnoatamir
authored andcommitted
STYLE/PERF: replace string concatenations with f-strings in core (pandas-dev#49518)
1 parent 043bd55 commit d270538

File tree

14 files changed

+22
-23
lines changed

14 files changed

+22
-23
lines changed

pandas/core/arrays/categorical.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -1882,7 +1882,7 @@ def _repr_categories_info(self) -> str:
18821882
start = True
18831883
cur_col_len = len(levheader) # header
18841884
sep_len, sep = (3, " < ") if self.ordered else (2, ", ")
1885-
linesep = sep.rstrip() + "\n" # remove whitespace
1885+
linesep = f"{sep.rstrip()}\n" # remove whitespace
18861886
for val in category_strs:
18871887
if max_width != 0 and cur_col_len + sep_len + len(val) > max_width:
18881888
levstring += linesep + (" " * (len(levheader) + 1))
@@ -1893,7 +1893,7 @@ def _repr_categories_info(self) -> str:
18931893
levstring += val
18941894
start = False
18951895
# replace to simple save space by
1896-
return levheader + "[" + levstring.replace(" < ... < ", " ... ") + "]"
1896+
return f"{levheader}[{levstring.replace(' < ... < ', ' ... ')}]"
18971897

18981898
def _repr_footer(self) -> str:
18991899
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

+2-2
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 (
@@ -1132,7 +1132,7 @@ def __new__(cls, subtype=None, closed: str_type | None = None):
11321132
)
11331133
raise TypeError(msg)
11341134

1135-
key = str(subtype) + str(closed)
1135+
key = f"{subtype}{closed}"
11361136
try:
11371137
return cls._cache_dtypes[key]
11381138
except KeyError:

pandas/core/frame.py

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

10991099
if get_option("display.notebook_repr_html"):
11001100
max_rows = get_option("display.max_rows")
@@ -8843,8 +8843,7 @@ def explode(
88438843
if not self.columns.is_unique:
88448844
duplicate_cols = self.columns[self.columns.duplicated()].tolist()
88458845
raise ValueError(
8846-
"DataFrame columns must be unique. "
8847-
+ f"Duplicate columns: {duplicate_cols}"
8846+
f"DataFrame columns must be unique. Duplicate columns: {duplicate_cols}"
88488847
)
88498848

88508849
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
@@ -337,7 +337,7 @@ def _format_attrs(self):
337337
attrs = [
338338
(
339339
"categories",
340-
"[" + ", ".join(self._data._repr_categories()) + "]",
340+
f"[{', '.join(self._data._repr_categories())}]",
341341
),
342342
("ordered", self.ordered),
343343
]

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

0 commit comments

Comments
 (0)