Skip to content

Commit b550011

Browse files
AlpAribalWillAyd
authored andcommitted
CLN: change str.format() to f-string (#30135)
1 parent f7b3dec commit b550011

File tree

9 files changed

+63
-109
lines changed

9 files changed

+63
-109
lines changed

pandas/core/arrays/string_.py

+5-7
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ def _validate(self):
171171
if self._ndarray.dtype != "object":
172172
raise ValueError(
173173
"StringArray requires a sequence of strings. Got "
174-
"'{}' dtype instead.".format(self._ndarray.dtype)
174+
f"'{self._ndarray.dtype}' dtype instead."
175175
)
176176

177177
@classmethod
@@ -222,7 +222,7 @@ def __setitem__(self, key, value):
222222
value = StringDtype.na_value
223223
elif not isinstance(value, str):
224224
raise ValueError(
225-
"Cannot set non-string value '{}' into a StringArray.".format(value)
225+
f"Cannot set non-string value '{value}' into a StringArray."
226226
)
227227
else:
228228
if not is_array_like(value):
@@ -245,7 +245,7 @@ def astype(self, dtype, copy=True):
245245
return super().astype(dtype, copy)
246246

247247
def _reduce(self, name, skipna=True, **kwargs):
248-
raise TypeError("Cannot perform reduction '{}' with string dtype".format(name))
248+
raise TypeError(f"Cannot perform reduction '{name}' with string dtype")
249249

250250
def value_counts(self, dropna=False):
251251
from pandas import value_counts
@@ -269,9 +269,7 @@ def method(self, other):
269269
if len(other) != len(self):
270270
# prevent improper broadcasting when other is 2D
271271
raise ValueError(
272-
"Lengths of operands do not match: {} != {}".format(
273-
len(self), len(other)
274-
)
272+
f"Lengths of operands do not match: {len(self)} != {len(other)}"
275273
)
276274

277275
other = np.asarray(other)
@@ -287,7 +285,7 @@ def method(self, other):
287285
dtype = "object" if mask.any() else "bool"
288286
return np.asarray(result, dtype=dtype)
289287

290-
return compat.set_function_name(method, "__{}__".format(op.__name__), cls)
288+
return compat.set_function_name(method, f"__{op.__name__}__", cls)
291289

292290
@classmethod
293291
def _add_arithmetic_ops(cls):

pandas/core/arrays/timedeltas.py

+15-40
Original file line numberDiff line numberDiff line change
@@ -70,15 +70,15 @@ def f(self):
7070
return result
7171

7272
f.__name__ = name
73-
f.__doc__ = "\n{}\n".format(docstring)
73+
f.__doc__ = f"\n{docstring}\n"
7474
return property(f)
7575

7676

7777
def _td_array_cmp(cls, op):
7878
"""
7979
Wrap comparison operations to convert timedelta-like to timedelta64
8080
"""
81-
opname = "__{name}__".format(name=op.__name__)
81+
opname = f"__{op.__name__}__"
8282
nat_result = opname == "__ne__"
8383

8484
@unpack_zerodim_and_defer(opname)
@@ -215,10 +215,10 @@ def __init__(self, values, dtype=_TD_DTYPE, freq=None, copy=False):
215215

216216
if not isinstance(values, np.ndarray):
217217
msg = (
218-
"Unexpected type '{}'. 'values' must be a TimedeltaArray "
219-
"ndarray, or Series or Index containing one of those."
218+
f"Unexpected type '{type(values).__name__}'. 'values' must be a"
219+
" TimedeltaArray ndarray, or Series or Index containing one of those."
220220
)
221-
raise ValueError(msg.format(type(values).__name__))
221+
raise ValueError(msg)
222222
if values.ndim != 1:
223223
raise ValueError("Only 1-dimensional input arrays are supported.")
224224

@@ -351,10 +351,7 @@ def _validate_fill_value(self, fill_value):
351351
elif isinstance(fill_value, (timedelta, np.timedelta64, Tick)):
352352
fill_value = Timedelta(fill_value).value
353353
else:
354-
raise ValueError(
355-
"'fill_value' should be a Timedelta. "
356-
"Got '{got}'.".format(got=fill_value)
357-
)
354+
raise ValueError(f"'fill_value' should be a Timedelta. Got '{fill_value}'.")
358355
return fill_value
359356

360357
def astype(self, dtype, copy=True):
@@ -461,9 +458,7 @@ def _format_native_types(self, na_rep="NaT", date_format=None):
461458
def _add_offset(self, other):
462459
assert not isinstance(other, Tick)
463460
raise TypeError(
464-
"cannot add the type {typ} to a {cls}".format(
465-
typ=type(other).__name__, cls=type(self).__name__
466-
)
461+
f"cannot add the type {type(other).__name__} to a {type(self).__name__}"
467462
)
468463

469464
def _add_delta(self, delta):
@@ -523,9 +518,7 @@ def _addsub_offset_array(self, other, op):
523518
return super()._addsub_offset_array(other, op)
524519
except AttributeError:
525520
raise TypeError(
526-
"Cannot add/subtract non-tick DateOffset to {cls}".format(
527-
cls=type(self).__name__
528-
)
521+
f"Cannot add/subtract non-tick DateOffset to {type(self).__name__}"
529522
)
530523

531524
def __mul__(self, other):
@@ -634,9 +627,7 @@ def __rtruediv__(self, other):
634627

635628
elif lib.is_scalar(other):
636629
raise TypeError(
637-
"Cannot divide {typ} by {cls}".format(
638-
typ=type(other).__name__, cls=type(self).__name__
639-
)
630+
f"Cannot divide {type(other).__name__} by {type(self).__name__}"
640631
)
641632

642633
if not hasattr(other, "dtype"):
@@ -659,9 +650,7 @@ def __rtruediv__(self, other):
659650

660651
else:
661652
raise TypeError(
662-
"Cannot divide {dtype} data by {cls}".format(
663-
dtype=other.dtype, cls=type(self).__name__
664-
)
653+
f"Cannot divide {other.dtype} data by {type(self).__name__}"
665654
)
666655

667656
def __floordiv__(self, other):
@@ -724,11 +713,7 @@ def __floordiv__(self, other):
724713

725714
else:
726715
dtype = getattr(other, "dtype", type(other).__name__)
727-
raise TypeError(
728-
"Cannot divide {typ} by {cls}".format(
729-
typ=dtype, cls=type(self).__name__
730-
)
731-
)
716+
raise TypeError(f"Cannot divide {dtype} by {type(self).__name__}")
732717

733718
def __rfloordiv__(self, other):
734719
if isinstance(other, (ABCSeries, ABCDataFrame, ABCIndexClass)):
@@ -749,9 +734,7 @@ def __rfloordiv__(self, other):
749734
return result
750735

751736
raise TypeError(
752-
"Cannot divide {typ} by {cls}".format(
753-
typ=type(other).__name__, cls=type(self).__name__
754-
)
737+
f"Cannot divide {type(other).__name__} by {type(self).__name__}"
755738
)
756739

757740
if not hasattr(other, "dtype"):
@@ -779,11 +762,7 @@ def __rfloordiv__(self, other):
779762

780763
else:
781764
dtype = getattr(other, "dtype", type(other).__name__)
782-
raise TypeError(
783-
"Cannot divide {typ} by {cls}".format(
784-
typ=dtype, cls=type(self).__name__
785-
)
786-
)
765+
raise TypeError(f"Cannot divide {dtype} by {type(self).__name__}")
787766

788767
def __mod__(self, other):
789768
# Note: This is a naive implementation, can likely be optimized
@@ -1056,11 +1035,7 @@ def sequence_to_td64ns(data, copy=False, unit="ns", errors="raise"):
10561035

10571036
else:
10581037
# This includes datetime64-dtype, see GH#23539, GH#29794
1059-
raise TypeError(
1060-
"dtype {dtype} cannot be converted to timedelta64[ns]".format(
1061-
dtype=data.dtype
1062-
)
1063-
)
1038+
raise TypeError(f"dtype {data.dtype} cannot be converted to timedelta64[ns]")
10641039

10651040
data = np.array(data, copy=copy)
10661041
if data.ndim != 1:
@@ -1096,7 +1071,7 @@ def ints_to_td64ns(data, unit="ns"):
10961071
copy_made = True
10971072

10981073
if unit != "ns":
1099-
dtype_str = "timedelta64[{unit}]".format(unit=unit)
1074+
dtype_str = f"timedelta64[{unit}]"
11001075
data = data.view(dtype_str)
11011076

11021077
# TODO: watch out for overflows when converting from lower-resolution

pandas/core/common.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -388,7 +388,7 @@ def standardize_mapping(into):
388388
return partial(collections.defaultdict, into.default_factory)
389389
into = type(into)
390390
if not issubclass(into, abc.Mapping):
391-
raise TypeError("unsupported type: {into}".format(into=into))
391+
raise TypeError(f"unsupported type: {into}")
392392
elif into == collections.defaultdict:
393393
raise TypeError("to_dict() only accepts initialized defaultdicts")
394394
return into

pandas/core/computation/engines.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,7 @@ def _check_ne_builtin_clash(expr):
3131
if overlap:
3232
s = ", ".join(repr(x) for x in overlap)
3333
raise NumExprClobberingError(
34-
'Variables in expression "{expr}" '
35-
"overlap with builtins: ({s})".format(expr=expr, s=s)
34+
f'Variables in expression "{expr}" overlap with builtins: ({s})'
3635
)
3736

3837

pandas/core/computation/expr.py

+13-18
Original file line numberDiff line numberDiff line change
@@ -282,10 +282,9 @@ def _filter_nodes(superclass, all_nodes=_all_nodes):
282282
# and we don't want `stmt` and friends in their so get only the class whose
283283
# names are capitalized
284284
_base_supported_nodes = (_all_node_names - _unsupported_nodes) | _hacked_nodes
285-
_msg = "cannot both support and not support {intersection}".format(
286-
intersection=_unsupported_nodes & _base_supported_nodes
287-
)
288-
assert not _unsupported_nodes & _base_supported_nodes, _msg
285+
intersection = _unsupported_nodes & _base_supported_nodes
286+
_msg = f"cannot both support and not support {intersection}"
287+
assert not intersection, _msg
289288

290289

291290
def _node_not_implemented(node_name, cls):
@@ -312,7 +311,7 @@ def disallowed(cls):
312311
cls.unsupported_nodes = ()
313312
for node in nodes:
314313
new_method = _node_not_implemented(node, cls)
315-
name = "visit_{node}".format(node=node)
314+
name = f"visit_{node}"
316315
cls.unsupported_nodes += (name,)
317316
setattr(cls, name, new_method)
318317
return cls
@@ -349,13 +348,13 @@ def add_ops(op_classes):
349348

350349
def f(cls):
351350
for op_attr_name, op_class in op_classes.items():
352-
ops = getattr(cls, "{name}_ops".format(name=op_attr_name))
353-
ops_map = getattr(cls, "{name}_op_nodes_map".format(name=op_attr_name))
351+
ops = getattr(cls, f"{op_attr_name}_ops")
352+
ops_map = getattr(cls, f"{op_attr_name}_op_nodes_map")
354353
for op in ops:
355354
op_node = ops_map[op]
356355
if op_node is not None:
357356
made_op = _op_maker(op_class, op)
358-
setattr(cls, "visit_{node}".format(node=op_node), made_op)
357+
setattr(cls, f"visit_{op_node}", made_op)
359358
return cls
360359

361360
return f
@@ -529,8 +528,8 @@ def _maybe_evaluate_binop(
529528

530529
if res.has_invalid_return_type:
531530
raise TypeError(
532-
"unsupported operand type(s) for {op}:"
533-
" '{lhs}' and '{rhs}'".format(op=res.op, lhs=lhs.type, rhs=rhs.type)
531+
f"unsupported operand type(s) for {res.op}:"
532+
f" '{lhs.type}' and '{rhs.type}'"
534533
)
535534

536535
if self.engine != "pytables":
@@ -677,7 +676,7 @@ def visit_Attribute(self, node, **kwargs):
677676
if isinstance(value, ast.Name) and value.id == attr:
678677
return resolved
679678

680-
raise ValueError("Invalid Attribute context {name}".format(name=ctx.__name__))
679+
raise ValueError(f"Invalid Attribute context {ctx.__name__}")
681680

682681
def visit_Call(self, node, side=None, **kwargs):
683682

@@ -697,7 +696,7 @@ def visit_Call(self, node, side=None, **kwargs):
697696
raise
698697

699698
if res is None:
700-
raise ValueError("Invalid function call {func}".format(func=node.func.id))
699+
raise ValueError(f"Invalid function call {node.func.id}")
701700
if hasattr(res, "value"):
702701
res = res.value
703702

@@ -707,8 +706,7 @@ def visit_Call(self, node, side=None, **kwargs):
707706

708707
if node.keywords:
709708
raise TypeError(
710-
'Function "{name}" does not support keyword '
711-
"arguments".format(name=res.name)
709+
f'Function "{res.name}" does not support keyword arguments'
712710
)
713711

714712
return res(*new_args, **kwargs)
@@ -719,10 +717,7 @@ def visit_Call(self, node, side=None, **kwargs):
719717

720718
for key in node.keywords:
721719
if not isinstance(key, ast.keyword):
722-
raise ValueError(
723-
"keyword error in function call "
724-
"'{func}'".format(func=node.func.id)
725-
)
720+
raise ValueError(f"keyword error in function call '{node.func.id}'")
726721

727722
if key.arg:
728723
kwargs[key.arg] = self.visit(key.value).value

pandas/core/computation/expressions.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,7 @@ def _evaluate_numexpr(op, op_str, a, b):
109109
b_value = getattr(b, "values", b)
110110

111111
result = ne.evaluate(
112-
"a_value {op} b_value".format(op=op_str),
112+
f"a_value {op_str} b_value",
113113
local_dict={"a_value": a_value, "b_value": b_value},
114114
casting="safe",
115115
)

pandas/core/computation/ops.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -212,8 +212,8 @@ def __repr__(self) -> str:
212212
Print a generic n-ary operator and its operands using infix notation.
213213
"""
214214
# recurse over the operands
215-
parened = ("({0})".format(pprint_thing(opr)) for opr in self.operands)
216-
return pprint_thing(" {0} ".format(self.op).join(parened))
215+
parened = (f"({pprint_thing(opr)})" for opr in self.operands)
216+
return pprint_thing(f" {self.op} ".join(parened))
217217

218218
@property
219219
def return_type(self):
@@ -506,8 +506,8 @@ def __init__(self, lhs, rhs, **kwargs):
506506

507507
if not isnumeric(lhs.return_type) or not isnumeric(rhs.return_type):
508508
raise TypeError(
509-
"unsupported operand type(s) for {0}:"
510-
" '{1}' and '{2}'".format(self.op, lhs.return_type, rhs.return_type)
509+
f"unsupported operand type(s) for {self.op}:"
510+
f" '{lhs.return_type}' and '{rhs.return_type}'"
511511
)
512512

513513
# do not upcast float32s to float64 un-necessarily
@@ -554,7 +554,7 @@ def __call__(self, env):
554554
return self.func(operand)
555555

556556
def __repr__(self) -> str:
557-
return pprint_thing("{0}({1})".format(self.op, self.operand))
557+
return pprint_thing(f"{self.op}({self.operand})")
558558

559559
@property
560560
def return_type(self) -> np.dtype:
@@ -580,7 +580,7 @@ def __call__(self, env):
580580

581581
def __repr__(self) -> str:
582582
operands = map(str, self.operands)
583-
return pprint_thing("{0}({1})".format(self.op, ",".join(operands)))
583+
return pprint_thing(f"{self.op}({','.join(operands)})")
584584

585585

586586
class FuncNode:
@@ -592,7 +592,7 @@ def __init__(self, name: str):
592592
and _NUMEXPR_VERSION < LooseVersion("2.6.9")
593593
and name in ("floor", "ceil")
594594
):
595-
raise ValueError('"{0}" is not a supported function'.format(name))
595+
raise ValueError(f'"{name}" is not a supported function')
596596

597597
self.name = name
598598
self.func = getattr(np, name)

0 commit comments

Comments
 (0)