From ec96d4581d6de512b06b101eccd8b19a2d101dde Mon Sep 17 00:00:00 2001 From: pineapplezz Date: Tue, 26 Nov 2019 11:17:38 -0500 Subject: [PATCH 1/7] Changed formatting to fstring --- pandas/tests/resample/test_datetime_index.py | 4 +--- pandas/tests/resample/test_time_grouper.py | 2 +- pandas/tests/tseries/offsets/common.py | 12 ++++-------- 3 files changed, 6 insertions(+), 12 deletions(-) diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py index a29f910261b58..f9229e8066be4 100644 --- a/pandas/tests/resample/test_datetime_index.py +++ b/pandas/tests/resample/test_datetime_index.py @@ -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})) diff --git a/pandas/tests/resample/test_time_grouper.py b/pandas/tests/resample/test_time_grouper.py index 574182ae99c5c..4c27d48cff6fd 100644 --- a/pandas/tests/resample/test_time_grouper.py +++ b/pandas/tests/resample/test_time_grouper.py @@ -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")) diff --git a/pandas/tests/tseries/offsets/common.py b/pandas/tests/tseries/offsets/common.py index fbf4454109ec0..a097636bbf0b4 100644 --- a/pandas/tests/tseries/offsets/common.py +++ b/pandas/tests/tseries/offsets/common.py @@ -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}" ) From 11d9dee84c25302130b45efbd7c92514b18747bb Mon Sep 17 00:00:00 2001 From: pineapplezz Date: Wed, 27 Nov 2019 13:09:45 -0500 Subject: [PATCH 2/7] Formatted .format to fstring --- pandas/errors/__init__.py | 8 +++----- pandas/tests/arrays/interval/test_ops.py | 4 +--- pandas/tests/arrays/sparse/test_array.py | 2 +- pandas/tests/arrays/sparse/test_libsparse.py | 2 +- pandas/tests/extension/arrow/arrays.py | 6 +++--- pandas/tests/extension/base/printing.py | 2 +- pandas/tests/extension/decimal/array.py | 6 +++--- pandas/tests/extension/decimal/test_decimal.py | 2 +- pandas/tests/extension/json/test_json.py | 2 +- pandas/tests/scalar/test_nat.py | 2 +- pandas/tseries/frequencies.py | 16 ++++++++-------- 11 files changed, 24 insertions(+), 28 deletions(-) diff --git a/pandas/errors/__init__.py b/pandas/errors/__init__.py index 73cc40ae0e0d3..e2f4cc0817e41 100644 --- a/pandas/errors/__init__.py +++ b/pandas/errors/__init__.py @@ -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 @@ -179,5 +177,5 @@ def __str__(self) -> str: name = self.class_instance.__name__ else: name = self.class_instance.__class__.__name__ - msg = "This {methodtype} must be defined in the concrete class {name}" - return msg.format(methodtype=self.methodtype, name=name) + msg = f"This {self.methodtype} must be defined in the concrete class {name}" + return msg \ No newline at end of file diff --git a/pandas/tests/arrays/interval/test_ops.py b/pandas/tests/arrays/interval/test_ops.py index 43601ea301568..a55c33c2f22e9 100644 --- a/pandas/tests/arrays/interval/test_ops.py +++ b/pandas/tests/arrays/interval/test_ops.py @@ -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) diff --git a/pandas/tests/arrays/sparse/test_array.py b/pandas/tests/arrays/sparse/test_array.py index 755cbfb716fcd..4866766df37d8 100644 --- a/pandas/tests/arrays/sparse/test_array.py +++ b/pandas/tests/arrays/sparse/test_array.py @@ -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 = f"axis\\(={axis}\\) out of bounds" with pytest.raises(ValueError, match=msg): SparseArray(data).cumsum(axis=axis) diff --git a/pandas/tests/arrays/sparse/test_libsparse.py b/pandas/tests/arrays/sparse/test_libsparse.py index a6836c58348b3..7a85ccf271e76 100644 --- a/pandas/tests/arrays/sparse/test_libsparse.py +++ b/pandas/tests/arrays/sparse/test_libsparse.py @@ -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) diff --git a/pandas/tests/extension/arrow/arrays.py b/pandas/tests/extension/arrow/arrays.py index 6a28f76e474cc..a4554aca1325e 100644 --- a/pandas/tests/extension/arrow/arrays.py +++ b/pandas/tests/extension/arrow/arrays.py @@ -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): @@ -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): @@ -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): diff --git a/pandas/tests/extension/base/printing.py b/pandas/tests/extension/base/printing.py index 0f10efbf32a49..de17a3a1d8edb 100644 --- a/pandas/tests/extension/base/printing.py +++ b/pandas/tests/extension/base/printing.py @@ -19,7 +19,7 @@ def test_array_repr(self, data, size): result = repr(data) assert data.__class__.__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 diff --git a/pandas/tests/extension/decimal/array.py b/pandas/tests/extension/decimal/array.py index f9ba4b7a8ba16..c884f35b8bad5 100644 --- a/pandas/tests/extension/decimal/array.py +++ b/pandas/tests/extension/decimal/array.py @@ -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): @@ -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): @@ -179,7 +179,7 @@ def _reduce(self, name, skipna=True, **kwargs): op = getattr(self.data, name) except AttributeError: raise NotImplementedError( - "decimal does not support the {} operation".format(name) + f"decimal does not support the {name} operation" ) return op(axis=0) diff --git a/pandas/tests/extension/decimal/test_decimal.py b/pandas/tests/extension/decimal/test_decimal.py index ce819c13c4498..a60ddb07ea61a 100644 --- a/pandas/tests/extension/decimal/test_decimal.py +++ b/pandas/tests/extension/decimal/test_decimal.py @@ -97,7 +97,7 @@ def assert_frame_equal(self, left, right, *args, **kwargs): check_names=kwargs.get("check_names", True), check_exact=kwargs.get("check_exact", False), check_categorical=kwargs.get("check_categorical", True), - obj="{obj}.columns".format(obj=kwargs.get("obj", "DataFrame")), + obj=f"{kwargs.get("obj", "DataFrame")}.columns", ) decimals = (left.dtypes == "decimal").index diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py index 7e027a65eec3a..0ebc59c6c6c79 100644 --- a/pandas/tests/extension/json/test_json.py +++ b/pandas/tests/extension/json/test_json.py @@ -100,7 +100,7 @@ def assert_frame_equal(self, left, right, *args, **kwargs): check_names=kwargs.get("check_names", True), check_exact=kwargs.get("check_exact", False), check_categorical=kwargs.get("check_categorical", True), - obj="{obj}.columns".format(obj=kwargs.get("obj", "DataFrame")), + obj=f"{kwargs.get("obj", "DataFrame")}.columns", ) jsons = (left.dtypes == "json").index diff --git a/pandas/tests/scalar/test_nat.py b/pandas/tests/scalar/test_nat.py index 79608f4fb3cde..e709db980b721 100644 --- a/pandas/tests/scalar/test_nat.py +++ b/pandas/tests/scalar/test_nat.py @@ -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)() diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py index 898060d011372..0fdd1291780d6 100644 --- a/pandas/tseries/frequencies.py +++ b/pandas/tseries/frequencies.py @@ -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 @@ -261,7 +261,7 @@ def infer_freq(index, warn=True): if isinstance(index, (pd.Int64Index, pd.Float64Index)): raise TypeError( "cannot infer freq from a non-convertible index " - "type {type}".format(type=type(index)) + f"type {type(index)}" ) index = index.values @@ -393,7 +393,7 @@ 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() @@ -401,7 +401,7 @@ def _infer_daily_rule(self): 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() @@ -413,7 +413,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) @@ -485,7 +485,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): @@ -495,7 +495,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) @@ -509,6 +509,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 From 7c4c1e61808606dcbcf83d6d1f8957fb72391474 Mon Sep 17 00:00:00 2001 From: pineapplezz Date: Wed, 27 Nov 2019 13:13:31 -0500 Subject: [PATCH 3/7] Fixed syntax --- pandas/tests/extension/decimal/test_decimal.py | 2 +- pandas/tests/extension/json/test_json.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/pandas/tests/extension/decimal/test_decimal.py b/pandas/tests/extension/decimal/test_decimal.py index a60ddb07ea61a..ce819c13c4498 100644 --- a/pandas/tests/extension/decimal/test_decimal.py +++ b/pandas/tests/extension/decimal/test_decimal.py @@ -97,7 +97,7 @@ def assert_frame_equal(self, left, right, *args, **kwargs): check_names=kwargs.get("check_names", True), check_exact=kwargs.get("check_exact", False), check_categorical=kwargs.get("check_categorical", True), - obj=f"{kwargs.get("obj", "DataFrame")}.columns", + obj="{obj}.columns".format(obj=kwargs.get("obj", "DataFrame")), ) decimals = (left.dtypes == "decimal").index diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py index 0ebc59c6c6c79..7e027a65eec3a 100644 --- a/pandas/tests/extension/json/test_json.py +++ b/pandas/tests/extension/json/test_json.py @@ -100,7 +100,7 @@ def assert_frame_equal(self, left, right, *args, **kwargs): check_names=kwargs.get("check_names", True), check_exact=kwargs.get("check_exact", False), check_categorical=kwargs.get("check_categorical", True), - obj=f"{kwargs.get("obj", "DataFrame")}.columns", + obj="{obj}.columns".format(obj=kwargs.get("obj", "DataFrame")), ) jsons = (left.dtypes == "json").index From 774e79ff43e92b5aacf5fddc3075864377b4ef2c Mon Sep 17 00:00:00 2001 From: pineapplezz Date: Wed, 27 Nov 2019 13:15:00 -0500 Subject: [PATCH 4/7] STYLE: Apply Black Formatting --- pandas/errors/__init__.py | 2 +- pandas/tests/extension/decimal/array.py | 4 +--- pandas/tseries/frequencies.py | 3 +-- 3 files changed, 3 insertions(+), 6 deletions(-) diff --git a/pandas/errors/__init__.py b/pandas/errors/__init__.py index e2f4cc0817e41..8e5db2cfd5a97 100644 --- a/pandas/errors/__init__.py +++ b/pandas/errors/__init__.py @@ -178,4 +178,4 @@ def __str__(self) -> str: else: name = self.class_instance.__class__.__name__ msg = f"This {self.methodtype} must be defined in the concrete class {name}" - return msg \ No newline at end of file + return msg diff --git a/pandas/tests/extension/decimal/array.py b/pandas/tests/extension/decimal/array.py index c884f35b8bad5..0c2f1e845909a 100644 --- a/pandas/tests/extension/decimal/array.py +++ b/pandas/tests/extension/decimal/array.py @@ -178,9 +178,7 @@ def _reduce(self, name, skipna=True, **kwargs): try: op = getattr(self.data, name) except AttributeError: - raise NotImplementedError( - f"decimal does not support the {name} operation" - ) + raise NotImplementedError(f"decimal does not support the {name} operation") return op(axis=0) diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py index 0fdd1291780d6..5108b5979c419 100644 --- a/pandas/tseries/frequencies.py +++ b/pandas/tseries/frequencies.py @@ -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 " - f"type {type(index)}" + "cannot infer freq from a non-convertible index " f"type {type(index)}" ) index = index.values From 180ef5245f88c3d44272cb60d89f45dab6808301 Mon Sep 17 00:00:00 2001 From: pineapplezz Date: Wed, 27 Nov 2019 14:18:11 -0500 Subject: [PATCH 5/7] STYLE: Fixed black formatting --- pandas/tseries/frequencies.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py index 5108b5979c419..9ff5fb41957b9 100644 --- a/pandas/tseries/frequencies.py +++ b/pandas/tseries/frequencies.py @@ -260,7 +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 " f"type {type(index)}" + f"cannot infer freq from a non-convertible index type {type(index)}" ) index = index.values From e80013fef887f18fb12afe78bfa01d99f53e5e6a Mon Sep 17 00:00:00 2001 From: pineapplezz Date: Mon, 2 Dec 2019 15:39:45 -0500 Subject: [PATCH 6/7] fstring formatting using re.escape --- pandas/tests/arrays/sparse/test_array.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pandas/tests/arrays/sparse/test_array.py b/pandas/tests/arrays/sparse/test_array.py index 4866766df37d8..c9f96ed516dc5 100644 --- a/pandas/tests/arrays/sparse/test_array.py +++ b/pandas/tests/arrays/sparse/test_array.py @@ -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 = f"axis\\(={axis}\\) out of bounds" + msg = re.escape(f"axis(={axis}) out of bounds") with pytest.raises(ValueError, match=msg): SparseArray(data).cumsum(axis=axis) From bff09de6b306b683fd0ce2bc1caa762c1da1ec3e Mon Sep 17 00:00:00 2001 From: pineapplezz Date: Tue, 26 Nov 2019 11:17:38 -0500 Subject: [PATCH 7/7] Changed formatting to fstring --- pandas/tests/resample/test_datetime_index.py | 4 +--- pandas/tests/resample/test_time_grouper.py | 2 +- pandas/tests/tseries/offsets/common.py | 12 ++++-------- 3 files changed, 6 insertions(+), 12 deletions(-) diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py index a29f910261b58..f9229e8066be4 100644 --- a/pandas/tests/resample/test_datetime_index.py +++ b/pandas/tests/resample/test_datetime_index.py @@ -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})) diff --git a/pandas/tests/resample/test_time_grouper.py b/pandas/tests/resample/test_time_grouper.py index 574182ae99c5c..4c27d48cff6fd 100644 --- a/pandas/tests/resample/test_time_grouper.py +++ b/pandas/tests/resample/test_time_grouper.py @@ -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")) diff --git a/pandas/tests/tseries/offsets/common.py b/pandas/tests/tseries/offsets/common.py index fbf4454109ec0..a097636bbf0b4 100644 --- a/pandas/tests/tseries/offsets/common.py +++ b/pandas/tests/tseries/offsets/common.py @@ -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}" )