Skip to content

CLN: f-string formatting #31868

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
Feb 11, 2020
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
4 changes: 2 additions & 2 deletions pandas/tests/indexes/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,7 +98,7 @@ def test_shift(self):

# GH8083 test the base class for shift
idx = self.create_index()
msg = "Not supported for type {}".format(type(idx).__name__)
msg = f"Not supported for type {type(idx).__name__}"
with pytest.raises(NotImplementedError, match=msg):
idx.shift(1)
with pytest.raises(NotImplementedError, match=msg):
Expand Down Expand Up @@ -808,7 +808,7 @@ def test_map_dictlike(self, mapper):

index = self.create_index()
if isinstance(index, (pd.CategoricalIndex, pd.IntervalIndex)):
pytest.skip("skipping tests for {}".format(type(index)))
pytest.skip(f"skipping tests for {type(index)}")

identity = mapper(index.values, index)

Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/indexes/datetimelike.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,15 @@ def test_str(self):
# test the string repr
idx = self.create_index()
idx.name = "foo"
assert not "length={}".format(len(idx)) in str(idx)
assert not (f"length={len(idx)}" in str(idx))
assert "'foo'" in str(idx)
assert type(idx).__name__ in str(idx)

if hasattr(idx, "tz"):
if idx.tz is not None:
assert idx.tz in str(idx)
if hasattr(idx, "freq"):
assert "freq='{idx.freqstr}'".format(idx=idx) in str(idx)
assert f"freq='{idx.freqstr}'" in str(idx)

def test_view(self):
i = self.create_index()
Expand Down
4 changes: 2 additions & 2 deletions pandas/tests/indexing/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@


def _mklbl(prefix, n):
return ["{prefix}{i}".format(prefix=prefix, i=i) for i in range(n)]
return [f"{prefix}{i}" for i in range(n)]


def _axify(obj, key, axis):
Expand Down Expand Up @@ -96,7 +96,7 @@ def setup_method(self, method):
for kind in self._kinds:
d = dict()
for typ in self._typs:
d[typ] = getattr(self, "{kind}_{typ}".format(kind=kind, typ=typ))
d[typ] = getattr(self, f"{kind}_{typ}")

setattr(self, kind, d)

Expand Down
6 changes: 2 additions & 4 deletions pandas/tests/indexing/test_coercion.py
Original file line number Diff line number Diff line change
Expand Up @@ -943,7 +943,7 @@ class TestReplaceSeriesCoercion(CoercionBase):

for tz in ["UTC", "US/Eastern"]:
# to test tz => different tz replacement
key = "datetime64[ns, {0}]".format(tz)
key = f"datetime64[ns, {tz}]"
rep[key] = [
pd.Timestamp("2011-01-01", tz=tz),
pd.Timestamp("2011-01-03", tz=tz),
Expand Down Expand Up @@ -1017,9 +1017,7 @@ def test_replace_series(self, how, to_key, from_key):
):

if compat.is_platform_32bit() or compat.is_platform_windows():
pytest.skip(
"32-bit platform buggy: {0} -> {1}".format(from_key, to_key)
)
pytest.skip(f"32-bit platform buggy: {from_key} -> {to_key}")

# Expected: do not downcast by replacement
exp = pd.Series(self.rep[to_key], index=index, name="yyy", dtype=from_key)
Expand Down
8 changes: 2 additions & 6 deletions pandas/tests/indexing/test_iloc.py
Original file line number Diff line number Diff line change
Expand Up @@ -246,9 +246,7 @@ def test_iloc_getitem_bool(self):
def test_iloc_getitem_bool_diff_len(self, index):
# GH26658
s = Series([1, 2, 3])
msg = "Boolean index has wrong length: {} instead of {}".format(
len(index), len(s)
)
msg = f"Boolean index has wrong length: {len(index)} instead of {len(s)}"
with pytest.raises(IndexError, match=msg):
_ = s.iloc[index]

Expand Down Expand Up @@ -612,9 +610,7 @@ def test_iloc_mask(self):
r = expected.get(key)
if r != ans:
raise AssertionError(
"[{key}] does not match [{ans}], received [{r}]".format(
key=key, ans=ans, r=r
)
f"[{key}] does not match [{ans}], received [{r}]"
)

def test_iloc_non_unique_indexing(self):
Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/indexing/test_indexing.py
Original file line number Diff line number Diff line change
Expand Up @@ -514,7 +514,7 @@ def __init__(self, value):
self.value = value

def __str__(self) -> str:
return "[{0}]".format(self.value)
return f"[{self.value}]"

__repr__ = __str__

Expand Down
12 changes: 3 additions & 9 deletions pandas/tests/indexing/test_loc.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,9 +217,7 @@ def test_getitem_label_list_with_missing(self):
def test_loc_getitem_bool_diff_len(self, index):
# GH26658
s = Series([1, 2, 3])
msg = "Boolean index has wrong length: {} instead of {}".format(
len(index), len(s)
)
msg = f"Boolean index has wrong length: {len(index)} instead of {len(s)}"
with pytest.raises(IndexError, match=msg):
_ = s.loc[index]

Expand Down Expand Up @@ -484,12 +482,8 @@ def test_loc_assign_non_ns_datetime(self, unit):
}
)

df.loc[:, unit] = df.loc[:, "timestamp"].values.astype(
"datetime64[{unit}]".format(unit=unit)
)
df["expected"] = df.loc[:, "timestamp"].values.astype(
"datetime64[{unit}]".format(unit=unit)
)
df.loc[:, unit] = df.loc[:, "timestamp"].values.astype(f"datetime64[{unit}]")
df["expected"] = df.loc[:, "timestamp"].values.astype(f"datetime64[{unit}]")
expected = Series(df.loc[:, "expected"], name=unit)
tm.assert_series_equal(df.loc[:, unit], expected)

Expand Down
2 changes: 1 addition & 1 deletion pandas/tests/series/methods/test_argsort.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def test_argsort(self, datetime_series):
assert issubclass(argsorted.dtype.type, np.integer)

# GH#2967 (introduced bug in 0.11-dev I think)
s = Series([Timestamp("201301{i:02d}".format(i=i)) for i in range(1, 6)])
s = Series([Timestamp(f"201301{i:02d}") for i in range(1, 6)])
assert s.dtype == "datetime64[ns]"
shifted = s.shift(-1)
assert shifted.dtype == "datetime64[ns]"
Expand Down
17 changes: 8 additions & 9 deletions pandas/tests/series/test_constructors.py
Original file line number Diff line number Diff line change
Expand Up @@ -811,15 +811,15 @@ def test_constructor_dtype_datetime64(self):
expected = Series(values2, index=dates)

for dtype in ["s", "D", "ms", "us", "ns"]:
values1 = dates.view(np.ndarray).astype("M8[{0}]".format(dtype))
values1 = dates.view(np.ndarray).astype(f"M8[{dtype}]")
result = Series(values1, dates)
tm.assert_series_equal(result, expected)

# GH 13876
# coerce to non-ns to object properly
expected = Series(values2, index=dates, dtype=object)
for dtype in ["s", "D", "ms", "us", "ns"]:
values1 = dates.view(np.ndarray).astype("M8[{0}]".format(dtype))
values1 = dates.view(np.ndarray).astype(f"M8[{dtype}]")
result = Series(values1, index=dates, dtype=object)
tm.assert_series_equal(result, expected)

Expand Down Expand Up @@ -952,7 +952,7 @@ def test_constructor_with_datetime_tz(self):
def test_construction_to_datetimelike_unit(self, arr_dtype, dtype, unit):
# tests all units
# gh-19223
dtype = "{}[{}]".format(dtype, unit)
dtype = f"{dtype}[{unit}]"
arr = np.array([1, 2, 3], dtype=arr_dtype)
s = Series(arr)
result = s.astype(dtype)
Expand Down Expand Up @@ -1347,12 +1347,11 @@ def test_convert_non_ns(self):
def test_constructor_cant_cast_datetimelike(self, index):

# floats are not ok
msg = "Cannot cast {}.*? to ".format(
# strip Index to convert PeriodIndex -> Period
# We don't care whether the error message says
# PeriodIndex or PeriodArray
type(index).__name__.rstrip("Index")
)
# strip Index to convert PeriodIndex -> Period
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I guess should move this comment before 1350 so it reads sequentially

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I was wondering about this, too

# We don't care whether the error message says
# PeriodIndex or PeriodArray
msg = f"Cannot cast {type(index).__name__.rstrip('Index')}.*? to "

with pytest.raises(TypeError, match=msg):
Series(index, dtype=float)

Expand Down
14 changes: 5 additions & 9 deletions pandas/tests/tseries/frequencies/test_inference.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ def test_infer_freq_delta(base_delta_code_pair, count):
inc = base_delta * count
index = DatetimeIndex([b + inc * j for j in range(3)])

exp_freq = "{count:d}{code}".format(count=count, code=code) if count > 1 else code
exp_freq = f"{count:d}{code}" if count > 1 else code
assert frequencies.infer_freq(index) == exp_freq


Expand All @@ -202,13 +202,11 @@ def test_infer_freq_custom(base_delta_code_pair, constructor):


def test_weekly_infer(periods, day):
_check_generated_range("1/1/2000", periods, "W-{day}".format(day=day))
_check_generated_range("1/1/2000", periods, f"W-{day}")


def test_week_of_month_infer(periods, day, count):
_check_generated_range(
"1/1/2000", periods, "WOM-{count}{day}".format(count=count, day=day)
)
_check_generated_range("1/1/2000", periods, f"WOM-{count}{day}")


@pytest.mark.parametrize("freq", ["M", "BM", "BMS"])
Expand All @@ -217,14 +215,12 @@ def test_monthly_infer(periods, freq):


def test_quarterly_infer(month, periods):
_check_generated_range("1/1/2000", periods, "Q-{month}".format(month=month))
_check_generated_range("1/1/2000", periods, f"Q-{month}")


@pytest.mark.parametrize("annual", ["A", "BA"])
def test_annually_infer(month, periods, annual):
_check_generated_range(
"1/1/2000", periods, "{annual}-{month}".format(annual=annual, month=month)
)
_check_generated_range("1/1/2000", periods, f"{annual}-{month}")


@pytest.mark.parametrize(
Expand Down