Skip to content

CLN: f-string in pandas/core/arrays/* #30124

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Dec 7, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 2 additions & 7 deletions pandas/core/arrays/_ranges.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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}"
)
20 changes: 7 additions & 13 deletions pandas/core/arrays/integer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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)}"
)


Expand Down Expand Up @@ -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
Expand All @@ -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)
Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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)


Expand Down
107 changes: 49 additions & 58 deletions pandas/core/arrays/interval.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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)
Expand All @@ -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 = (
Expand All @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -630,19 +627,18 @@ 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))
# TODO: This try/except will be repeated.
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):
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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):
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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
Expand Down
16 changes: 6 additions & 10 deletions pandas/core/arrays/numpy_.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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]

Expand Down Expand Up @@ -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))
Expand Down Expand Up @@ -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

Expand Down
Loading