Skip to content

String formatting > fstring #29892

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 8 commits into from
Dec 4, 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
6 changes: 2 additions & 4 deletions pandas/errors/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,9 +167,7 @@ class AbstractMethodError(NotImplementedError):
def __init__(self, class_instance, methodtype="method"):
types = {"method", "classmethod", "staticmethod", "property"}
if methodtype not in types:
msg = "methodtype must be one of {}, got {} instead.".format(
methodtype, types
)
msg = f"methodtype must be one of {methodtype}, got {types} instead."
raise ValueError(msg)
self.methodtype = methodtype
self.class_instance = class_instance
Expand All @@ -179,5 +177,5 @@ def __str__(self) -> str:
name = self.class_instance.__name__
else:
name = type(self.class_instance).__name__
msg = "This {methodtype} must be defined in the concrete class {name}"
msg = f"This {self.methodtype} must be defined in the concrete class {name}"
return msg.format(methodtype=self.methodtype, name=name)
4 changes: 1 addition & 3 deletions pandas/tests/arrays/interval/test_ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,6 @@ def test_overlaps_na(self, constructor, start_shift):
)
def test_overlaps_invalid_type(self, constructor, other):
interval_container = constructor.from_breaks(range(5))
msg = "`other` must be Interval-like, got {other}".format(
other=type(other).__name__
)
msg = f"`other` must be Interval-like, got {type(other).__name__}"
with pytest.raises(TypeError, match=msg):
interval_container.overlaps(other)
2 changes: 1 addition & 1 deletion pandas/tests/arrays/sparse/test_array.py
Original file line number Diff line number Diff line change
Expand Up @@ -1007,7 +1007,7 @@ def test_cumsum(self, data, expected, numpy):
np.cumsum(SparseArray(data), out=out)
else:
axis = 1 # SparseArray currently 1-D, so only axis = 0 is valid.
msg = "axis\\(={axis}\\) out of bounds".format(axis=axis)
msg = re.escape(f"axis(={axis}) out of bounds")
with pytest.raises(ValueError, match=msg):
SparseArray(data).cumsum(axis=axis)

Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/arrays/sparse/test_libsparse.py
Original file line number Diff line number Diff line change
Expand Up @@ -596,6 +596,6 @@ def _check_case(xloc, xlen, yloc, ylen, eloc, elen):

@pytest.mark.parametrize("opname", ["add", "sub", "mul", "truediv", "floordiv"])
def test_op(self, opname):
sparse_op = getattr(splib, "sparse_{opname}_float64".format(opname=opname))
sparse_op = getattr(splib, f"sparse_{opname}_float64")
python_op = getattr(operator, opname)
self._op_tests(sparse_op, python_op)
6 changes: 3 additions & 3 deletions pandas/tests/extension/arrow/arrays.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def construct_from_string(cls, string):
if string == cls.name:
return cls()
else:
raise TypeError("Cannot construct a '{}' from '{}'".format(cls, string))
raise TypeError(f"Cannot construct a '{cls}' from '{string}'")

@classmethod
def construct_array_type(cls):
Expand All @@ -56,7 +56,7 @@ def construct_from_string(cls, string):
if string == cls.name:
return cls()
else:
raise TypeError("Cannot construct a '{}' from '{}'".format(cls, string))
raise TypeError(f"Cannot construct a '{cls}' from '{string}'")

@classmethod
def construct_array_type(cls):
Expand All @@ -79,7 +79,7 @@ def _from_sequence(cls, scalars, dtype=None, copy=False):
return cls.from_scalars(scalars)

def __repr__(self):
return "{cls}({data})".format(cls=type(self).__name__, data=repr(self._data))
return f"{type(self).__name__}({repr(self._data)})"

def __getitem__(self, item):
if pd.api.types.is_scalar(item):
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/extension/base/printing.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ def test_array_repr(self, data, size):

result = repr(data)
assert type(data).__name__ in result
assert "Length: {}".format(len(data)) in result
assert f"Length: {len(data)}" in result
assert str(data.dtype) in result
if size == "big":
assert "..." in result
Expand Down
8 changes: 3 additions & 5 deletions pandas/tests/extension/decimal/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def __init__(self, context=None):
self.context = context or decimal.getcontext()

def __repr__(self) -> str:
return "DecimalDtype(context={})".format(self.context)
return f"DecimalDtype(context={self.context})"

@classmethod
def construct_array_type(cls):
Expand All @@ -40,7 +40,7 @@ def construct_from_string(cls, string):
if string == cls.name:
return cls()
else:
raise TypeError("Cannot construct a '{}' from '{}'".format(cls, string))
raise TypeError(f"Cannot construct a '{cls}' from '{string}'")

@property
def _is_numeric(self):
Expand Down Expand Up @@ -178,9 +178,7 @@ def _reduce(self, name, skipna=True, **kwargs):
try:
op = getattr(self.data, name)
except AttributeError:
raise NotImplementedError(
"decimal does not support the {} operation".format(name)
)
raise NotImplementedError(f"decimal does not support the {name} operation")
return op(axis=0)


Expand Down
4 changes: 1 addition & 3 deletions pandas/tests/resample/test_datetime_index.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,9 +146,7 @@ def test_resample_basic_grouper(series):
def test_resample_string_kwargs(series, keyword, value):
# see gh-19303
# Check that wrong keyword argument strings raise an error
msg = "Unsupported value {value} for `{keyword}`".format(
value=value, keyword=keyword
)
msg = f"Unsupported value {value} for `{keyword}`"
with pytest.raises(ValueError, match=msg):
series.resample("5min", **({keyword: value}))

Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/resample/test_time_grouper.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ def test_fails_on_no_datetime_index(name, func):

msg = (
"Only valid with DatetimeIndex, TimedeltaIndex "
"or PeriodIndex, but got an instance of '{}'".format(name)
f"or PeriodIndex, but got an instance of '{name}'"
)
with pytest.raises(TypeError, match=msg):
df.groupby(Grouper(freq="D"))
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/scalar/test_nat.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ def test_round_nat(klass, method, freq):
)
def test_nat_methods_raise(method):
# see gh-9513, gh-17329
msg = "NaTType does not support {method}".format(method=method)
msg = f"NaTType does not support {method}"

with pytest.raises(ValueError, match=msg):
getattr(NaT, method)()
Expand Down
12 changes: 4 additions & 8 deletions pandas/tests/tseries/offsets/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,18 +13,14 @@ def assert_offset_equal(offset, base, expected):
assert actual_apply == expected
except AssertionError:
raise AssertionError(
"\nExpected: {expected}\nActual: {actual}\nFor Offset: {offset})"
"\nAt Date: {base}".format(
expected=expected, actual=actual, offset=offset, base=base
)
f"\nExpected: {expected}\nActual: {actual}\nFor Offset: {offset})"
f"\nAt Date: {base}"
)


def assert_onOffset(offset, date, expected):
actual = offset.onOffset(date)
assert actual == expected, (
"\nExpected: {expected}\nActual: {actual}\nFor Offset: {offset})"
"\nAt Date: {date}".format(
expected=expected, actual=actual, offset=offset, date=date
)
f"\nExpected: {expected}\nActual: {actual}\nFor Offset: {offset})"
f"\nAt Date: {date}"
)
17 changes: 8 additions & 9 deletions pandas/tseries/frequencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,7 @@ def infer_freq(index, warn=True):
):
raise TypeError(
"cannot infer freq from a non-convertible dtype "
"on a Series of {dtype}".format(dtype=index.dtype)
f"on a Series of {index.dtype}"
)
index = values

Expand All @@ -260,8 +260,7 @@ def infer_freq(index, warn=True):
if isinstance(index, pd.Index) and not isinstance(index, pd.DatetimeIndex):
if isinstance(index, (pd.Int64Index, pd.Float64Index)):
raise TypeError(
"cannot infer freq from a non-convertible index "
"type {type}".format(type=type(index))
f"cannot infer freq from a non-convertible index type {type(index)}"
)
index = index.values

Expand Down Expand Up @@ -393,15 +392,15 @@ def _infer_daily_rule(self):
if annual_rule:
nyears = self.ydiffs[0]
month = MONTH_ALIASES[self.rep_stamp.month]
alias = "{prefix}-{month}".format(prefix=annual_rule, month=month)
alias = f"{annual_rule}-{month}"
return _maybe_add_count(alias, nyears)

quarterly_rule = self._get_quarterly_rule()
if quarterly_rule:
nquarters = self.mdiffs[0] / 3
mod_dict = {0: 12, 2: 11, 1: 10}
month = MONTH_ALIASES[mod_dict[self.rep_stamp.month % 3]]
alias = "{prefix}-{month}".format(prefix=quarterly_rule, month=month)
alias = f"{quarterly_rule}-{month}"
return _maybe_add_count(alias, nquarters)

monthly_rule = self._get_monthly_rule()
Expand All @@ -413,7 +412,7 @@ def _infer_daily_rule(self):
if days % 7 == 0:
# Weekly
day = int_to_weekday[self.rep_stamp.weekday()]
return _maybe_add_count("W-{day}".format(day=day), days / 7)
return _maybe_add_count(f"W-{day}", days / 7)
else:
return _maybe_add_count("D", days)

Expand Down Expand Up @@ -485,7 +484,7 @@ def _get_wom_rule(self):
week = week_of_months[0] + 1
wd = int_to_weekday[weekdays[0]]

return "WOM-{week}{weekday}".format(week=week, weekday=wd)
return f"WOM-{week}{wd}"


class _TimedeltaFrequencyInferer(_FrequencyInferer):
Expand All @@ -495,7 +494,7 @@ def _infer_daily_rule(self):
if days % 7 == 0:
# Weekly
wd = int_to_weekday[self.rep_stamp.weekday()]
alias = "W-{weekday}".format(weekday=wd)
alias = f"W-{wd}"
return _maybe_add_count(alias, days / 7)
else:
return _maybe_add_count("D", days)
Expand All @@ -509,6 +508,6 @@ def _maybe_add_count(base, count):
if count != 1:
assert count == int(count)
count = int(count)
return "{count}{base}".format(count=count, base=base)
return f"{count}{base}"
else:
return base