diff --git a/pandas/core/arrays/_ranges.py b/pandas/core/arrays/_ranges.py index 15ff1432f16e2..2cae2c9250ea5 100644 --- a/pandas/core/arrays/_ranges.py +++ b/pandas/core/arrays/_ranges.py @@ -114,10 +114,7 @@ def _generate_range_overflow_safe( assert side in ["start", "end"] i64max = np.uint64(np.iinfo(np.int64).max) - msg = ( - "Cannot generate range with {side}={endpoint} and " - "periods={periods}".format(side=side, endpoint=endpoint, periods=periods) - ) + msg = f"Cannot generate range with {side}={endpoint} and periods={periods}" with np.errstate(over="raise"): # if periods * strides cannot be multiplied within the *uint64* bounds, @@ -190,7 +187,5 @@ def _generate_range_overflow_safe_signed( return result raise OutOfBoundsDatetime( - "Cannot generate range with " - "{side}={endpoint} and " - "periods={periods}".format(side=side, endpoint=endpoint, periods=periods) + f"Cannot generate range with {side}={endpoint} and periods={periods}" ) diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py index 12b76df9a5983..2bfb53aa1c800 100644 --- a/pandas/core/arrays/integer.py +++ b/pandas/core/arrays/integer.py @@ -47,7 +47,7 @@ class _IntegerDtype(ExtensionDtype): def __repr__(self) -> str: sign = "U" if self.is_unsigned_integer else "" - return "{sign}Int{size}Dtype()".format(sign=sign, size=8 * self.itemsize) + return f"{sign}Int{8 * self.itemsize}Dtype()" @cache_readonly def is_signed_integer(self): @@ -155,9 +155,7 @@ def safe_cast(values, dtype, copy): return casted raise TypeError( - "cannot safely cast non-equivalent {} to {}".format( - values.dtype, np.dtype(dtype) - ) + f"cannot safely cast non-equivalent {values.dtype} to {np.dtype(dtype)}" ) @@ -194,7 +192,7 @@ def coerce_to_array(values, dtype, mask=None, copy=False): try: dtype = _dtypes[str(np.dtype(dtype))] except KeyError: - raise ValueError("invalid dtype specified {}".format(dtype)) + raise ValueError(f"invalid dtype specified {dtype}") if isinstance(values, IntegerArray): values, mask = values._data, values._mask @@ -219,17 +217,13 @@ def coerce_to_array(values, dtype, mask=None, copy=False): "integer-na", "mixed-integer-float", ]: - raise TypeError( - "{} cannot be converted to an IntegerDtype".format(values.dtype) - ) + raise TypeError(f"{values.dtype} cannot be converted to an IntegerDtype") elif is_bool_dtype(values) and is_integer_dtype(dtype): values = np.array(values, dtype=int, copy=copy) elif not (is_integer_dtype(values) or is_float_dtype(values)): - raise TypeError( - "{} cannot be converted to an IntegerDtype".format(values.dtype) - ) + raise TypeError(f"{values.dtype} cannot be converted to an IntegerDtype") if mask is None: mask = isna(values) @@ -663,7 +657,7 @@ def cmp_method(self, other): result[mask] = op_name == "ne" return result - name = "__{name}__".format(name=op.__name__) + name = f"__{op.__name__}__" return set_function_name(cmp_method, name, cls) def _reduce(self, name, skipna=True, **kwargs): @@ -773,7 +767,7 @@ def integer_arithmetic_method(self, other): return self._maybe_mask_result(result, mask, other, op_name) - name = "__{name}__".format(name=op.__name__) + name = f"__{op.__name__}__" return set_function_name(integer_arithmetic_method, name, cls) diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index ab558b8fa75d6..cea059fb22be1 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -159,10 +159,10 @@ def __new__(cls, data, closed=None, dtype=None, copy=False, verify_integrity=Tru # don't allow scalars if is_scalar(data): msg = ( - "{}(...) must be called with a collection of some kind," - " {} was passed" + f"{cls.__name__}(...) must be called with a collection " + f"of some kind, {data} was passed" ) - raise TypeError(msg.format(cls.__name__, data)) + raise TypeError(msg) # might need to convert empty or purely na data data = maybe_convert_platform_interval(data) @@ -194,8 +194,8 @@ def _simple_new( # GH 19262: dtype must be an IntervalDtype to override inferred dtype = pandas_dtype(dtype) if not is_interval_dtype(dtype): - msg = "dtype must be an IntervalDtype, got {dtype}" - raise TypeError(msg.format(dtype=dtype)) + msg = f"dtype must be an IntervalDtype, got {dtype}" + raise TypeError(msg) elif dtype.subtype is not None: left = left.astype(dtype.subtype) right = right.astype(dtype.subtype) @@ -207,10 +207,11 @@ def _simple_new( left = left.astype(right.dtype) if type(left) != type(right): - msg = "must not have differing left [{ltype}] and right [{rtype}] types" - raise ValueError( - msg.format(ltype=type(left).__name__, rtype=type(right).__name__) + msg = ( + f"must not have differing left [{type(left).__name__}] and " + f"right [{type(right).__name__}] types" ) + raise ValueError(msg) elif is_categorical_dtype(left.dtype) or is_string_dtype(left.dtype): # GH 19016 msg = ( @@ -224,9 +225,9 @@ def _simple_new( elif isinstance(left, ABCDatetimeIndex) and str(left.tz) != str(right.tz): msg = ( "left and right must have the same time zone, got " - "'{left_tz}' and '{right_tz}'" + f"'{left.tz}' and '{right.tz}'" ) - raise ValueError(msg.format(left_tz=left.tz, right_tz=right.tz)) + raise ValueError(msg) result._left = left result._right = right @@ -443,14 +444,10 @@ def from_tuples(cls, data, closed="right", copy=False, dtype=None): # need list of length 2 tuples, e.g. [(0, 1), (1, 2), ...] lhs, rhs = d except ValueError: - msg = ( - "{name}.from_tuples requires tuples of length 2, got {tpl}" - ).format(name=name, tpl=d) + msg = f"{name}.from_tuples requires tuples of length 2, got {d}" raise ValueError(msg) except TypeError: - msg = ("{name}.from_tuples received an invalid item, {tpl}").format( - name=name, tpl=d - ) + msg = f"{name}.from_tuples received an invalid item, {d}" raise TypeError(msg) left.append(lhs) right.append(rhs) @@ -468,20 +465,22 @@ def _validate(self): * left is always below right """ if self.closed not in _VALID_CLOSED: - raise ValueError( - "invalid option for 'closed': {closed}".format(closed=self.closed) - ) + msg = f"invalid option for 'closed': {self.closed}" + raise ValueError(msg) if len(self.left) != len(self.right): - raise ValueError("left and right must have the same length") + msg = "left and right must have the same length" + raise ValueError(msg) left_mask = notna(self.left) right_mask = notna(self.right) if not (left_mask == right_mask).all(): - raise ValueError( + msg = ( "missing values must be missing in the same " "location both left and right sides" ) + raise ValueError(msg) if not (self.left[left_mask] <= self.right[left_mask]).all(): - raise ValueError("left side of interval must be <= right side") + msg = "left side of interval must be <= right side" + raise ValueError(msg) # --------- # Interface @@ -531,8 +530,8 @@ def __setitem__(self, key, value): value_left, value_right = array.left, array.right except TypeError: # wrong type: not interval or NA - msg = "'value' should be an interval type, got {} instead." - raise TypeError(msg.format(type(value))) + msg = f"'value' should be an interval type, got {type(value)} instead." + raise TypeError(msg) # Need to ensure that left and right are updated atomically, so we're # 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): if not isinstance(value, ABCInterval): msg = ( "'IntervalArray.fillna' only supports filling with a " - "scalar 'pandas.Interval'. Got a '{}' instead.".format( - type(value).__name__ - ) + f"scalar 'pandas.Interval'. Got a '{type(value).__name__}' instead." ) raise TypeError(msg) @@ -630,10 +627,9 @@ def astype(self, dtype, copy=True): new_right = self.right.astype(dtype.subtype) except TypeError: msg = ( - "Cannot convert {dtype} to {new_dtype}; subtypes are " - "incompatible" + f"Cannot convert {self.dtype} to {dtype}; subtypes are incompatible" ) - raise TypeError(msg.format(dtype=self.dtype, new_dtype=dtype)) + raise TypeError(msg) return self._shallow_copy(new_left, new_right) elif is_categorical_dtype(dtype): return Categorical(np.asarray(self)) @@ -641,8 +637,8 @@ def astype(self, dtype, copy=True): try: return np.asarray(self).astype(dtype, copy=copy) except (TypeError, ValueError): - msg = "Cannot cast {name} to dtype {dtype}" - raise TypeError(msg.format(name=type(self).__name__, dtype=dtype)) + msg = f"Cannot cast {type(self).__name__} to dtype {dtype}" + raise TypeError(msg) @classmethod def _concat_same_type(cls, to_concat): @@ -790,9 +786,8 @@ def take(self, indices, allow_fill=False, fill_value=None, axis=None, **kwargs): elif not is_scalar(fill_value) and notna(fill_value): msg = ( "'IntervalArray.fillna' only supports filling with a " - "'scalar pandas.Interval or NA'. Got a '{}' instead.".format( - type(fill_value).__name__ - ) + "'scalar pandas.Interval or NA'. " + f"Got a '{type(fill_value).__name__}' instead." ) raise ValueError(msg) @@ -840,48 +835,44 @@ def _format_data(self): summary = "[]" elif n == 1: first = formatter(self[0]) - summary = "[{first}]".format(first=first) + summary = f"[{first}]" elif n == 2: first = formatter(self[0]) last = formatter(self[-1]) - summary = "[{first}, {last}]".format(first=first, last=last) + summary = f"[{first}, {last}]" else: if n > max_seq_items: n = min(max_seq_items // 2, 10) head = [formatter(x) for x in self[:n]] tail = [formatter(x) for x in self[-n:]] - summary = "[{head} ... {tail}]".format( - head=", ".join(head), tail=", ".join(tail) - ) + head_str = ", ".join(head) + tail_str = ", ".join(tail) + summary = f"[{head_str} ... {tail_str}]" else: tail = [formatter(x) for x in self] - summary = "[{tail}]".format(tail=", ".join(tail)) + tail_str = ", ".join(tail) + summary = f"[{tail_str}]" return summary def __repr__(self) -> str: - template = ( - "{class_name}" - "{data}\n" - "Length: {length}, closed: {closed}, dtype: {dtype}" - ) # the short repr has no trailing newline, while the truncated # repr does. So we include a newline in our template, and strip # any trailing newlines from format_object_summary data = self._format_data() - class_name = "<{}>\n".format(type(self).__name__) - return template.format( - class_name=class_name, - data=data, - length=len(self), - closed=self.closed, - dtype=self.dtype, + class_name = f"<{type(self).__name__}>\n" + + template = ( + f"{class_name}" + f"{data}\n" + f"Length: {len(self)}, closed: {self.closed}, dtype: {self.dtype}" ) + return template def _format_space(self): space = " " * (len(type(self).__name__) + 1) - return "\n{space}".format(space=space) + return f"\n{space}" @property def left(self): @@ -951,8 +942,8 @@ def closed(self): ) def set_closed(self, closed): if closed not in _VALID_CLOSED: - msg = "invalid option for 'closed': {closed}" - raise ValueError(msg.format(closed=closed)) + msg = f"invalid option for 'closed': {closed}" + raise ValueError(msg) return self._shallow_copy(closed=closed) @@ -1188,8 +1179,8 @@ def overlaps(self, other): if isinstance(other, (IntervalArray, ABCIntervalIndex)): raise NotImplementedError elif not isinstance(other, Interval): - msg = "`other` must be Interval-like, got {other}" - raise TypeError(msg.format(other=type(other).__name__)) + msg = f"`other` must be Interval-like, got {type(other).__name__}" + raise TypeError(msg) # equality is okay if both endpoints are closed (overlap at a point) op1 = le if (self.closed_left and other.closed_right) else lt diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py index e116d180e3a14..bc7de0e2c4e1e 100644 --- a/pandas/core/arrays/numpy_.py +++ b/pandas/core/arrays/numpy_.py @@ -128,9 +128,7 @@ def __init__(self, values: Union[np.ndarray, "PandasArray"], copy: bool = False) values = values._ndarray if not isinstance(values, np.ndarray): raise ValueError( - "'values' must be a NumPy array, not {typ}".format( - typ=type(values).__name__ - ) + f"'values' must be a NumPy array, not {type(values).__name__}" ) if values.ndim != 1: @@ -261,8 +259,8 @@ def fillna(self, value=None, method=None, limit=None): if is_array_like(value): if len(value) != len(self): raise ValueError( - "Length of 'value' does not match. Got ({}) " - " expected {}".format(len(value), len(self)) + f"Length of 'value' does not match. Got ({len(value)}) " + f" expected {len(self)}" ) value = value[mask] @@ -308,8 +306,8 @@ def _reduce(self, name, skipna=True, **kwargs): if meth: return meth(skipna=skipna, **kwargs) else: - msg = "'{}' does not implement reduction '{}'" - raise TypeError(msg.format(type(self).__name__, name)) + msg = f"'{type(self).__name__}' does not implement reduction '{name}'" + raise TypeError(msg) def any(self, axis=None, out=None, keepdims=False, skipna=True): nv.validate_any((), dict(out=out, keepdims=keepdims)) @@ -456,9 +454,7 @@ def arithmetic_method(self, other): return cls(result) - return compat.set_function_name( - arithmetic_method, "__{}__".format(op.__name__), cls - ) + return compat.set_function_name(arithmetic_method, f"__{op.__name__}__", cls) _create_comparison_method = _create_arithmetic_method diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 1012abd0b5d13..df057ce5a0104 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -65,7 +65,7 @@ def _period_array_cmp(cls, op): """ Wrap comparison operations to convert Period-like to PeriodDtype """ - opname = "__{name}__".format(name=op.__name__) + opname = f"__{op.__name__}__" nat_result = opname == "__ne__" @unpack_zerodim_and_defer(opname) @@ -302,9 +302,7 @@ def _unbox_scalar(self, value: Union[Period, NaTType]) -> int: self._check_compatible_with(value) return value.ordinal else: - raise ValueError( - "'value' should be a Period. Got '{val}' instead.".format(val=value) - ) + raise ValueError(f"'value' should be a Period. Got '{value}' instead.") def _scalar_from_string(self, value: str) -> Period: return Period(value, freq=self.freq) @@ -491,10 +489,7 @@ def _validate_fill_value(self, fill_value): self._check_compatible_with(fill_value) fill_value = fill_value.ordinal else: - raise ValueError( - "'fill_value' should be a Period. " - "Got '{got}'.".format(got=fill_value) - ) + raise ValueError(f"'fill_value' should be a Period. Got '{fill_value}'.") return fill_value # -------------------------------------------------------------------- @@ -517,7 +512,7 @@ def _time_shift(self, periods, freq=None): if freq is not None: raise TypeError( "`freq` argument is not supported for " - "{cls}._time_shift".format(cls=type(self).__name__) + f"{type(self).__name__}._time_shift" ) values = self.asi8 + periods * self.freq.n if self._hasnans: @@ -954,7 +949,7 @@ def dt64arr_to_periodarr(data, freq, tz=None): """ if data.dtype != np.dtype("M8[ns]"): - raise ValueError("Wrong dtype: {dtype}".format(dtype=data.dtype)) + raise ValueError(f"Wrong dtype: {data.dtype}") if freq is None: if isinstance(data, ABCIndexClass):