Skip to content

Commit 86faeb1

Browse files
ganevgvproost
authored andcommitted
CLN: f-string in pandas/core/arrays/* (pandas-dev#30124)
1 parent c08056a commit 86faeb1

File tree

5 files changed

+69
-98
lines changed

5 files changed

+69
-98
lines changed

pandas/core/arrays/_ranges.py

+2-7
Original file line numberDiff line numberDiff line change
@@ -114,10 +114,7 @@ def _generate_range_overflow_safe(
114114
assert side in ["start", "end"]
115115

116116
i64max = np.uint64(np.iinfo(np.int64).max)
117-
msg = (
118-
"Cannot generate range with {side}={endpoint} and "
119-
"periods={periods}".format(side=side, endpoint=endpoint, periods=periods)
120-
)
117+
msg = f"Cannot generate range with {side}={endpoint} and periods={periods}"
121118

122119
with np.errstate(over="raise"):
123120
# if periods * strides cannot be multiplied within the *uint64* bounds,
@@ -190,7 +187,5 @@ def _generate_range_overflow_safe_signed(
190187
return result
191188

192189
raise OutOfBoundsDatetime(
193-
"Cannot generate range with "
194-
"{side}={endpoint} and "
195-
"periods={periods}".format(side=side, endpoint=endpoint, periods=periods)
190+
f"Cannot generate range with {side}={endpoint} and periods={periods}"
196191
)

pandas/core/arrays/integer.py

+7-13
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ class _IntegerDtype(ExtensionDtype):
4747

4848
def __repr__(self) -> str:
4949
sign = "U" if self.is_unsigned_integer else ""
50-
return "{sign}Int{size}Dtype()".format(sign=sign, size=8 * self.itemsize)
50+
return f"{sign}Int{8 * self.itemsize}Dtype()"
5151

5252
@cache_readonly
5353
def is_signed_integer(self):
@@ -155,9 +155,7 @@ def safe_cast(values, dtype, copy):
155155
return casted
156156

157157
raise TypeError(
158-
"cannot safely cast non-equivalent {} to {}".format(
159-
values.dtype, np.dtype(dtype)
160-
)
158+
f"cannot safely cast non-equivalent {values.dtype} to {np.dtype(dtype)}"
161159
)
162160

163161

@@ -194,7 +192,7 @@ def coerce_to_array(values, dtype, mask=None, copy=False):
194192
try:
195193
dtype = _dtypes[str(np.dtype(dtype))]
196194
except KeyError:
197-
raise ValueError("invalid dtype specified {}".format(dtype))
195+
raise ValueError(f"invalid dtype specified {dtype}")
198196

199197
if isinstance(values, IntegerArray):
200198
values, mask = values._data, values._mask
@@ -219,17 +217,13 @@ def coerce_to_array(values, dtype, mask=None, copy=False):
219217
"integer-na",
220218
"mixed-integer-float",
221219
]:
222-
raise TypeError(
223-
"{} cannot be converted to an IntegerDtype".format(values.dtype)
224-
)
220+
raise TypeError(f"{values.dtype} cannot be converted to an IntegerDtype")
225221

226222
elif is_bool_dtype(values) and is_integer_dtype(dtype):
227223
values = np.array(values, dtype=int, copy=copy)
228224

229225
elif not (is_integer_dtype(values) or is_float_dtype(values)):
230-
raise TypeError(
231-
"{} cannot be converted to an IntegerDtype".format(values.dtype)
232-
)
226+
raise TypeError(f"{values.dtype} cannot be converted to an IntegerDtype")
233227

234228
if mask is None:
235229
mask = isna(values)
@@ -663,7 +657,7 @@ def cmp_method(self, other):
663657
result[mask] = op_name == "ne"
664658
return result
665659

666-
name = "__{name}__".format(name=op.__name__)
660+
name = f"__{op.__name__}__"
667661
return set_function_name(cmp_method, name, cls)
668662

669663
def _reduce(self, name, skipna=True, **kwargs):
@@ -773,7 +767,7 @@ def integer_arithmetic_method(self, other):
773767

774768
return self._maybe_mask_result(result, mask, other, op_name)
775769

776-
name = "__{name}__".format(name=op.__name__)
770+
name = f"__{op.__name__}__"
777771
return set_function_name(integer_arithmetic_method, name, cls)
778772

779773

pandas/core/arrays/interval.py

+49-58
Original file line numberDiff line numberDiff line change
@@ -159,10 +159,10 @@ def __new__(cls, data, closed=None, dtype=None, copy=False, verify_integrity=Tru
159159
# don't allow scalars
160160
if is_scalar(data):
161161
msg = (
162-
"{}(...) must be called with a collection of some kind,"
163-
" {} was passed"
162+
f"{cls.__name__}(...) must be called with a collection "
163+
f"of some kind, {data} was passed"
164164
)
165-
raise TypeError(msg.format(cls.__name__, data))
165+
raise TypeError(msg)
166166

167167
# might need to convert empty or purely na data
168168
data = maybe_convert_platform_interval(data)
@@ -194,8 +194,8 @@ def _simple_new(
194194
# GH 19262: dtype must be an IntervalDtype to override inferred
195195
dtype = pandas_dtype(dtype)
196196
if not is_interval_dtype(dtype):
197-
msg = "dtype must be an IntervalDtype, got {dtype}"
198-
raise TypeError(msg.format(dtype=dtype))
197+
msg = f"dtype must be an IntervalDtype, got {dtype}"
198+
raise TypeError(msg)
199199
elif dtype.subtype is not None:
200200
left = left.astype(dtype.subtype)
201201
right = right.astype(dtype.subtype)
@@ -207,10 +207,11 @@ def _simple_new(
207207
left = left.astype(right.dtype)
208208

209209
if type(left) != type(right):
210-
msg = "must not have differing left [{ltype}] and right [{rtype}] types"
211-
raise ValueError(
212-
msg.format(ltype=type(left).__name__, rtype=type(right).__name__)
210+
msg = (
211+
f"must not have differing left [{type(left).__name__}] and "
212+
f"right [{type(right).__name__}] types"
213213
)
214+
raise ValueError(msg)
214215
elif is_categorical_dtype(left.dtype) or is_string_dtype(left.dtype):
215216
# GH 19016
216217
msg = (
@@ -224,9 +225,9 @@ def _simple_new(
224225
elif isinstance(left, ABCDatetimeIndex) and str(left.tz) != str(right.tz):
225226
msg = (
226227
"left and right must have the same time zone, got "
227-
"'{left_tz}' and '{right_tz}'"
228+
f"'{left.tz}' and '{right.tz}'"
228229
)
229-
raise ValueError(msg.format(left_tz=left.tz, right_tz=right.tz))
230+
raise ValueError(msg)
230231

231232
result._left = left
232233
result._right = right
@@ -443,14 +444,10 @@ def from_tuples(cls, data, closed="right", copy=False, dtype=None):
443444
# need list of length 2 tuples, e.g. [(0, 1), (1, 2), ...]
444445
lhs, rhs = d
445446
except ValueError:
446-
msg = (
447-
"{name}.from_tuples requires tuples of length 2, got {tpl}"
448-
).format(name=name, tpl=d)
447+
msg = f"{name}.from_tuples requires tuples of length 2, got {d}"
449448
raise ValueError(msg)
450449
except TypeError:
451-
msg = ("{name}.from_tuples received an invalid item, {tpl}").format(
452-
name=name, tpl=d
453-
)
450+
msg = f"{name}.from_tuples received an invalid item, {d}"
454451
raise TypeError(msg)
455452
left.append(lhs)
456453
right.append(rhs)
@@ -468,20 +465,22 @@ def _validate(self):
468465
* left is always below right
469466
"""
470467
if self.closed not in _VALID_CLOSED:
471-
raise ValueError(
472-
"invalid option for 'closed': {closed}".format(closed=self.closed)
473-
)
468+
msg = f"invalid option for 'closed': {self.closed}"
469+
raise ValueError(msg)
474470
if len(self.left) != len(self.right):
475-
raise ValueError("left and right must have the same length")
471+
msg = "left and right must have the same length"
472+
raise ValueError(msg)
476473
left_mask = notna(self.left)
477474
right_mask = notna(self.right)
478475
if not (left_mask == right_mask).all():
479-
raise ValueError(
476+
msg = (
480477
"missing values must be missing in the same "
481478
"location both left and right sides"
482479
)
480+
raise ValueError(msg)
483481
if not (self.left[left_mask] <= self.right[left_mask]).all():
484-
raise ValueError("left side of interval must be <= right side")
482+
msg = "left side of interval must be <= right side"
483+
raise ValueError(msg)
485484

486485
# ---------
487486
# Interface
@@ -531,8 +530,8 @@ def __setitem__(self, key, value):
531530
value_left, value_right = array.left, array.right
532531
except TypeError:
533532
# wrong type: not interval or NA
534-
msg = "'value' should be an interval type, got {} instead."
535-
raise TypeError(msg.format(type(value)))
533+
msg = f"'value' should be an interval type, got {type(value)} instead."
534+
raise TypeError(msg)
536535

537536
# Need to ensure that left and right are updated atomically, so we're
538537
# forced to copy, update the copy, and swap in the new values.
@@ -583,9 +582,7 @@ def fillna(self, value=None, method=None, limit=None):
583582
if not isinstance(value, ABCInterval):
584583
msg = (
585584
"'IntervalArray.fillna' only supports filling with a "
586-
"scalar 'pandas.Interval'. Got a '{}' instead.".format(
587-
type(value).__name__
588-
)
585+
f"scalar 'pandas.Interval'. Got a '{type(value).__name__}' instead."
589586
)
590587
raise TypeError(msg)
591588

@@ -630,19 +627,18 @@ def astype(self, dtype, copy=True):
630627
new_right = self.right.astype(dtype.subtype)
631628
except TypeError:
632629
msg = (
633-
"Cannot convert {dtype} to {new_dtype}; subtypes are "
634-
"incompatible"
630+
f"Cannot convert {self.dtype} to {dtype}; subtypes are incompatible"
635631
)
636-
raise TypeError(msg.format(dtype=self.dtype, new_dtype=dtype))
632+
raise TypeError(msg)
637633
return self._shallow_copy(new_left, new_right)
638634
elif is_categorical_dtype(dtype):
639635
return Categorical(np.asarray(self))
640636
# TODO: This try/except will be repeated.
641637
try:
642638
return np.asarray(self).astype(dtype, copy=copy)
643639
except (TypeError, ValueError):
644-
msg = "Cannot cast {name} to dtype {dtype}"
645-
raise TypeError(msg.format(name=type(self).__name__, dtype=dtype))
640+
msg = f"Cannot cast {type(self).__name__} to dtype {dtype}"
641+
raise TypeError(msg)
646642

647643
@classmethod
648644
def _concat_same_type(cls, to_concat):
@@ -790,9 +786,8 @@ def take(self, indices, allow_fill=False, fill_value=None, axis=None, **kwargs):
790786
elif not is_scalar(fill_value) and notna(fill_value):
791787
msg = (
792788
"'IntervalArray.fillna' only supports filling with a "
793-
"'scalar pandas.Interval or NA'. Got a '{}' instead.".format(
794-
type(fill_value).__name__
795-
)
789+
"'scalar pandas.Interval or NA'. "
790+
f"Got a '{type(fill_value).__name__}' instead."
796791
)
797792
raise ValueError(msg)
798793

@@ -840,48 +835,44 @@ def _format_data(self):
840835
summary = "[]"
841836
elif n == 1:
842837
first = formatter(self[0])
843-
summary = "[{first}]".format(first=first)
838+
summary = f"[{first}]"
844839
elif n == 2:
845840
first = formatter(self[0])
846841
last = formatter(self[-1])
847-
summary = "[{first}, {last}]".format(first=first, last=last)
842+
summary = f"[{first}, {last}]"
848843
else:
849844

850845
if n > max_seq_items:
851846
n = min(max_seq_items // 2, 10)
852847
head = [formatter(x) for x in self[:n]]
853848
tail = [formatter(x) for x in self[-n:]]
854-
summary = "[{head} ... {tail}]".format(
855-
head=", ".join(head), tail=", ".join(tail)
856-
)
849+
head_str = ", ".join(head)
850+
tail_str = ", ".join(tail)
851+
summary = f"[{head_str} ... {tail_str}]"
857852
else:
858853
tail = [formatter(x) for x in self]
859-
summary = "[{tail}]".format(tail=", ".join(tail))
854+
tail_str = ", ".join(tail)
855+
summary = f"[{tail_str}]"
860856

861857
return summary
862858

863859
def __repr__(self) -> str:
864-
template = (
865-
"{class_name}"
866-
"{data}\n"
867-
"Length: {length}, closed: {closed}, dtype: {dtype}"
868-
)
869860
# the short repr has no trailing newline, while the truncated
870861
# repr does. So we include a newline in our template, and strip
871862
# any trailing newlines from format_object_summary
872863
data = self._format_data()
873-
class_name = "<{}>\n".format(type(self).__name__)
874-
return template.format(
875-
class_name=class_name,
876-
data=data,
877-
length=len(self),
878-
closed=self.closed,
879-
dtype=self.dtype,
864+
class_name = f"<{type(self).__name__}>\n"
865+
866+
template = (
867+
f"{class_name}"
868+
f"{data}\n"
869+
f"Length: {len(self)}, closed: {self.closed}, dtype: {self.dtype}"
880870
)
871+
return template
881872

882873
def _format_space(self):
883874
space = " " * (len(type(self).__name__) + 1)
884-
return "\n{space}".format(space=space)
875+
return f"\n{space}"
885876

886877
@property
887878
def left(self):
@@ -951,8 +942,8 @@ def closed(self):
951942
)
952943
def set_closed(self, closed):
953944
if closed not in _VALID_CLOSED:
954-
msg = "invalid option for 'closed': {closed}"
955-
raise ValueError(msg.format(closed=closed))
945+
msg = f"invalid option for 'closed': {closed}"
946+
raise ValueError(msg)
956947

957948
return self._shallow_copy(closed=closed)
958949

@@ -1188,8 +1179,8 @@ def overlaps(self, other):
11881179
if isinstance(other, (IntervalArray, ABCIntervalIndex)):
11891180
raise NotImplementedError
11901181
elif not isinstance(other, Interval):
1191-
msg = "`other` must be Interval-like, got {other}"
1192-
raise TypeError(msg.format(other=type(other).__name__))
1182+
msg = f"`other` must be Interval-like, got {type(other).__name__}"
1183+
raise TypeError(msg)
11931184

11941185
# equality is okay if both endpoints are closed (overlap at a point)
11951186
op1 = le if (self.closed_left and other.closed_right) else lt

pandas/core/arrays/numpy_.py

+6-10
Original file line numberDiff line numberDiff line change
@@ -128,9 +128,7 @@ def __init__(self, values: Union[np.ndarray, "PandasArray"], copy: bool = False)
128128
values = values._ndarray
129129
if not isinstance(values, np.ndarray):
130130
raise ValueError(
131-
"'values' must be a NumPy array, not {typ}".format(
132-
typ=type(values).__name__
133-
)
131+
f"'values' must be a NumPy array, not {type(values).__name__}"
134132
)
135133

136134
if values.ndim != 1:
@@ -261,8 +259,8 @@ def fillna(self, value=None, method=None, limit=None):
261259
if is_array_like(value):
262260
if len(value) != len(self):
263261
raise ValueError(
264-
"Length of 'value' does not match. Got ({}) "
265-
" expected {}".format(len(value), len(self))
262+
f"Length of 'value' does not match. Got ({len(value)}) "
263+
f" expected {len(self)}"
266264
)
267265
value = value[mask]
268266

@@ -308,8 +306,8 @@ def _reduce(self, name, skipna=True, **kwargs):
308306
if meth:
309307
return meth(skipna=skipna, **kwargs)
310308
else:
311-
msg = "'{}' does not implement reduction '{}'"
312-
raise TypeError(msg.format(type(self).__name__, name))
309+
msg = f"'{type(self).__name__}' does not implement reduction '{name}'"
310+
raise TypeError(msg)
313311

314312
def any(self, axis=None, out=None, keepdims=False, skipna=True):
315313
nv.validate_any((), dict(out=out, keepdims=keepdims))
@@ -456,9 +454,7 @@ def arithmetic_method(self, other):
456454

457455
return cls(result)
458456

459-
return compat.set_function_name(
460-
arithmetic_method, "__{}__".format(op.__name__), cls
461-
)
457+
return compat.set_function_name(arithmetic_method, f"__{op.__name__}__", cls)
462458

463459
_create_comparison_method = _create_arithmetic_method
464460

0 commit comments

Comments
 (0)