diff --git a/pandas/tests/frame/indexing/test_getitem.py b/pandas/tests/frame/indexing/test_getitem.py index 9d9324f557c8d..ecd8d1e988fd8 100644 --- a/pandas/tests/frame/indexing/test_getitem.py +++ b/pandas/tests/frame/indexing/test_getitem.py @@ -42,9 +42,6 @@ def test_getitem_periodindex(self): ts = df[rng[0]] tm.assert_series_equal(ts, df.iloc[:, 0]) - # GH#1211; smoketest unrelated to the rest of this test - repr(df) - ts = df["1/1/2000"] tm.assert_series_equal(ts, df.iloc[:, 0]) @@ -372,8 +369,6 @@ def test_getitem_boolean_series_with_duplicate_columns(self, df_dup_cols): result = df[df.C > 6] tm.assert_frame_equal(result, expected) - result.dtypes - str(result) def test_getitem_boolean_frame_with_duplicate_columns(self, df_dup_cols): # where @@ -388,8 +383,6 @@ def test_getitem_boolean_frame_with_duplicate_columns(self, df_dup_cols): result = df[df > 6] tm.assert_frame_equal(result, expected) - result.dtypes - str(result) def test_getitem_empty_frame_with_boolean(self): # Test for issue GH#11859 diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index ba8d713df5787..58581941509e8 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -511,7 +511,6 @@ def test_setitem_None(self, float_frame): float_frame.loc[:, None], float_frame["A"], check_names=False ) tm.assert_series_equal(float_frame[None], float_frame["A"], check_names=False) - repr(float_frame) def test_loc_setitem_boolean_mask_allfalse(self): # GH 9596 diff --git a/pandas/tests/frame/indexing/test_insert.py b/pandas/tests/frame/indexing/test_insert.py index 12229c28e0a80..7e702bdc993bd 100644 --- a/pandas/tests/frame/indexing/test_insert.py +++ b/pandas/tests/frame/indexing/test_insert.py @@ -51,14 +51,12 @@ def test_insert_column_bug_4032(self): df.insert(0, "a", [1, 2]) result = df.rename(columns={}) - str(result) expected = DataFrame([[1, 1.1], [2, 2.2]], columns=["a", "b"]) tm.assert_frame_equal(result, expected) df.insert(0, "c", [1.3, 2.3]) result = df.rename(columns={}) - str(result) expected = DataFrame([[1.3, 1, 1.1], [2.3, 2, 2.2]], columns=["c", "a", "b"]) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py index 1317e3767efba..49dd7a3c4df9b 100644 --- a/pandas/tests/frame/indexing/test_setitem.py +++ b/pandas/tests/frame/indexing/test_setitem.py @@ -868,8 +868,6 @@ def test_setitem_with_expansion_categorical_dtype(self): # setting with a Categorical df["D"] = cat - str(df) - result = df.dtypes expected = Series( [np.dtype("int32"), CategoricalDtype(categories=labels, ordered=False)], @@ -879,8 +877,6 @@ def test_setitem_with_expansion_categorical_dtype(self): # setting with a Series df["E"] = ser - str(df) - result = df.dtypes expected = Series( [ diff --git a/pandas/tests/frame/methods/test_rename.py b/pandas/tests/frame/methods/test_rename.py index f35cb21f378bb..b965a5d973fb6 100644 --- a/pandas/tests/frame/methods/test_rename.py +++ b/pandas/tests/frame/methods/test_rename.py @@ -387,8 +387,6 @@ def test_rename_with_duplicate_columns(self): # TODO: can we construct this without merge? k = merge(df4, df5, how="inner", left_index=True, right_index=True) result = k.rename(columns={"TClose_x": "TClose", "TClose_y": "QT_Close"}) - str(result) - result.dtypes expected = DataFrame( [[0.0454, 22.02, 0.0422, 20130331, 600809, "饡驦", 30.01]], diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py index b0e4bc95b3fb8..da5a2c21023b7 100644 --- a/pandas/tests/frame/test_arithmetic.py +++ b/pandas/tests/frame/test_arithmetic.py @@ -689,8 +689,6 @@ def test_arithmetic_with_duplicate_columns(self, op): df.columns = ["A", "A"] result = getattr(df, op)(df) tm.assert_frame_equal(result, expected) - str(result) - result.dtypes @pytest.mark.parametrize("level", [0, None]) def test_broadcast_multiindex(self, level): diff --git a/pandas/tests/frame/test_nonunique_indexes.py b/pandas/tests/frame/test_nonunique_indexes.py index 8f4b7d27e45f3..12aeede2560b8 100644 --- a/pandas/tests/frame/test_nonunique_indexes.py +++ b/pandas/tests/frame/test_nonunique_indexes.py @@ -10,13 +10,6 @@ import pandas._testing as tm -def check(result, expected=None): - if expected is not None: - tm.assert_frame_equal(result, expected) - result.dtypes - str(result) - - class TestDataFrameNonuniqueIndexes: def test_setattr_columns_vs_construct_with_columns(self): # assignment @@ -26,7 +19,7 @@ def test_setattr_columns_vs_construct_with_columns(self): df = DataFrame(arr, columns=["A", "A"]) df.columns = idx expected = DataFrame(arr, columns=idx) - check(df, expected) + tm.assert_frame_equal(df, expected) def test_setattr_columns_vs_construct_with_columns_datetimeindx(self): idx = date_range("20130101", periods=4, freq="QE-NOV") @@ -35,7 +28,7 @@ def test_setattr_columns_vs_construct_with_columns_datetimeindx(self): ) df.columns = idx expected = DataFrame([[1, 1, 1, 5], [1, 1, 2, 5], [2, 1, 3, 5]], columns=idx) - check(df, expected) + tm.assert_frame_equal(df, expected) def test_insert_with_duplicate_columns(self): # insert @@ -48,7 +41,7 @@ def test_insert_with_duplicate_columns(self): [[1, 1, 1, 5, "bah"], [1, 1, 2, 5, "bah"], [2, 1, 3, 5, "bah"]], columns=["foo", "bar", "foo", "hello", "string"], ) - check(df, expected) + tm.assert_frame_equal(df, expected) with pytest.raises(ValueError, match="Length of value"): df.insert(0, "AnotherColumn", range(len(df.index) - 1)) @@ -58,7 +51,7 @@ def test_insert_with_duplicate_columns(self): [[1, 1, 1, 5, "bah", 3], [1, 1, 2, 5, "bah", 3], [2, 1, 3, 5, "bah", 3]], columns=["foo", "bar", "foo", "hello", "string", "foo2"], ) - check(df, expected) + tm.assert_frame_equal(df, expected) # set (non-dup) df["foo2"] = 4 @@ -66,7 +59,7 @@ def test_insert_with_duplicate_columns(self): [[1, 1, 1, 5, "bah", 4], [1, 1, 2, 5, "bah", 4], [2, 1, 3, 5, "bah", 4]], columns=["foo", "bar", "foo", "hello", "string", "foo2"], ) - check(df, expected) + tm.assert_frame_equal(df, expected) df["foo2"] = 3 # delete (non dup) @@ -75,7 +68,7 @@ def test_insert_with_duplicate_columns(self): [[1, 1, 5, "bah", 3], [1, 2, 5, "bah", 3], [2, 3, 5, "bah", 3]], columns=["foo", "foo", "hello", "string", "foo2"], ) - check(df, expected) + tm.assert_frame_equal(df, expected) # try to delete again (its not consolidated) del df["hello"] @@ -83,7 +76,7 @@ def test_insert_with_duplicate_columns(self): [[1, 1, "bah", 3], [1, 2, "bah", 3], [2, 3, "bah", 3]], columns=["foo", "foo", "string", "foo2"], ) - check(df, expected) + tm.assert_frame_equal(df, expected) # consolidate df = df._consolidate() @@ -91,7 +84,7 @@ def test_insert_with_duplicate_columns(self): [[1, 1, "bah", 3], [1, 2, "bah", 3], [2, 3, "bah", 3]], columns=["foo", "foo", "string", "foo2"], ) - check(df, expected) + tm.assert_frame_equal(df, expected) # insert df.insert(2, "new_col", 5.0) @@ -99,7 +92,7 @@ def test_insert_with_duplicate_columns(self): [[1, 1, 5.0, "bah", 3], [1, 2, 5.0, "bah", 3], [2, 3, 5.0, "bah", 3]], columns=["foo", "foo", "new_col", "string", "foo2"], ) - check(df, expected) + tm.assert_frame_equal(df, expected) # insert a dup with pytest.raises(ValueError, match="cannot insert"): @@ -114,7 +107,7 @@ def test_insert_with_duplicate_columns(self): ], columns=["foo", "foo", "new_col", "new_col", "string", "foo2"], ) - check(df, expected) + tm.assert_frame_equal(df, expected) # delete (dup) del df["foo"] @@ -130,18 +123,17 @@ def test_dup_across_dtypes(self): [[1, 1, 1.0, 5], [1, 1, 2.0, 5], [2, 1, 3.0, 5]], columns=["foo", "bar", "foo", "hello"], ) - check(df) df["foo2"] = 7.0 expected = DataFrame( [[1, 1, 1.0, 5, 7.0], [1, 1, 2.0, 5, 7.0], [2, 1, 3.0, 5, 7.0]], columns=["foo", "bar", "foo", "hello", "foo2"], ) - check(df, expected) + tm.assert_frame_equal(df, expected) result = df["foo"] expected = DataFrame([[1, 1.0], [1, 2.0], [2, 3.0]], columns=["foo", "foo"]) - check(result, expected) + tm.assert_frame_equal(result, expected) # multiple replacements df["foo"] = "string" @@ -153,13 +145,13 @@ def test_dup_across_dtypes(self): ], columns=["foo", "bar", "foo", "hello", "foo2"], ) - check(df, expected) + tm.assert_frame_equal(df, expected) del df["foo"] expected = DataFrame( [[1, 5, 7.0], [1, 5, 7.0], [1, 5, 7.0]], columns=["bar", "hello", "foo2"] ) - check(df, expected) + tm.assert_frame_equal(df, expected) def test_column_dups_indexes(self): # check column dups with index equal and not equal to df's index @@ -176,7 +168,7 @@ def test_column_dups_indexes(self): columns=["A", "B", "A"], ) this_df["A"] = index - check(this_df, expected_df) + tm.assert_frame_equal(this_df, expected_df) def test_changing_dtypes_with_duplicate_columns(self): # multiple assignments that change dtypes @@ -188,7 +180,7 @@ def test_changing_dtypes_with_duplicate_columns(self): expected = DataFrame(1.0, index=range(5), columns=["that", "that"]) df["that"] = 1.0 - check(df, expected) + tm.assert_frame_equal(df, expected) df = DataFrame( np.random.default_rng(2).random((5, 2)), columns=["that", "that"] @@ -196,7 +188,7 @@ def test_changing_dtypes_with_duplicate_columns(self): expected = DataFrame(1, index=range(5), columns=["that", "that"]) df["that"] = 1 - check(df, expected) + tm.assert_frame_equal(df, expected) def test_dup_columns_comparisons(self): # equality @@ -231,7 +223,7 @@ def test_mixed_column_selection(self): ) expected = pd.concat([dfbool["one"], dfbool["three"], dfbool["one"]], axis=1) result = dfbool[["one", "three", "one"]] - check(result, expected) + tm.assert_frame_equal(result, expected) def test_multi_axis_dups(self): # multi-axis dups @@ -251,7 +243,7 @@ def test_multi_axis_dups(self): ) z = df[["A", "C", "A"]] result = z.loc[["a", "c", "a"]] - check(result, expected) + tm.assert_frame_equal(result, expected) def test_columns_with_dups(self): # GH 3468 related @@ -259,13 +251,11 @@ def test_columns_with_dups(self): # basic df = DataFrame([[1, 2]], columns=["a", "a"]) df.columns = ["a", "a.1"] - str(df) expected = DataFrame([[1, 2]], columns=["a", "a.1"]) tm.assert_frame_equal(df, expected) df = DataFrame([[1, 2, 3]], columns=["b", "a", "a"]) df.columns = ["b", "a", "a.1"] - str(df) expected = DataFrame([[1, 2, 3]], columns=["b", "a", "a.1"]) tm.assert_frame_equal(df, expected) @@ -273,7 +263,6 @@ def test_columns_with_dup_index(self): # with a dup index df = DataFrame([[1, 2]], columns=["a", "a"]) df.columns = ["b", "b"] - str(df) expected = DataFrame([[1, 2]], columns=["b", "b"]) tm.assert_frame_equal(df, expected) @@ -284,7 +273,6 @@ def test_multi_dtype(self): columns=["a", "a", "b", "b", "d", "c", "c"], ) df.columns = list("ABCDEFG") - str(df) expected = DataFrame( [[1, 2, 1.0, 2.0, 3.0, "foo", "bar"]], columns=list("ABCDEFG") ) @@ -293,7 +281,6 @@ def test_multi_dtype(self): def test_multi_dtype2(self): df = DataFrame([[1, 2, "foo", "bar"]], columns=["a", "a", "a", "a"]) df.columns = ["a", "a.1", "a.2", "a.3"] - str(df) expected = DataFrame([[1, 2, "foo", "bar"]], columns=["a", "a.1", "a.2", "a.3"]) tm.assert_frame_equal(df, expected) diff --git a/pandas/tests/frame/test_repr.py b/pandas/tests/frame/test_repr.py index 7c0e374c50bab..cb6713ae0f73c 100644 --- a/pandas/tests/frame/test_repr.py +++ b/pandas/tests/frame/test_repr.py @@ -10,7 +10,9 @@ from pandas import ( NA, Categorical, + CategoricalIndex, DataFrame, + IntervalIndex, MultiIndex, NaT, PeriodIndex, @@ -26,6 +28,21 @@ class TestDataFrameRepr: + def test_repr_should_return_str(self): + # https://docs.python.org/3/reference/datamodel.html#object.__repr__ + # "...The return value must be a string object." + + # (str on py2.x, str (unicode) on py3) + + data = [8, 5, 3, 5] + index1 = ["\u03c3", "\u03c4", "\u03c5", "\u03c6"] + cols = ["\u03c8"] + df = DataFrame(data, columns=cols, index=index1) + assert type(df.__repr__()) is str # noqa: E721 + + ser = df[cols[0]] + assert type(ser.__repr__()) is str # noqa: E721 + def test_repr_bytes_61_lines(self): # GH#12857 lets = list("ACDEFGHIJKLMNOP") @@ -291,6 +308,27 @@ def test_latex_repr(self): # GH 12182 assert df._repr_latex_() is None + def test_repr_with_datetimeindex(self): + df = DataFrame({"A": [1, 2, 3]}, index=date_range("2000", periods=3)) + result = repr(df) + expected = " A\n2000-01-01 1\n2000-01-02 2\n2000-01-03 3" + assert result == expected + + def test_repr_with_intervalindex(self): + # https://github.com/pandas-dev/pandas/pull/24134/files + df = DataFrame( + {"A": [1, 2, 3, 4]}, index=IntervalIndex.from_breaks([0, 1, 2, 3, 4]) + ) + result = repr(df) + expected = " A\n(0, 1] 1\n(1, 2] 2\n(2, 3] 3\n(3, 4] 4" + assert result == expected + + def test_repr_with_categorical_index(self): + df = DataFrame({"A": [1, 2, 3]}, index=CategoricalIndex(["a", "b", "c"])) + result = repr(df) + expected = " A\na 1\nb 2\nc 3" + assert result == expected + def test_repr_categorical_dates_periods(self): # normal DataFrame dt = date_range("2011-01-01 09:00", freq="h", periods=5, tz="US/Eastern") diff --git a/pandas/tests/indexes/base_class/test_formats.py b/pandas/tests/indexes/base_class/test_formats.py index 20f94010f56f8..379aea8826414 100644 --- a/pandas/tests/indexes/base_class/test_formats.py +++ b/pandas/tests/indexes/base_class/test_formats.py @@ -8,6 +8,13 @@ class TestIndexRendering: + def test_repr_is_valid_construction_code(self): + # for the case of Index, where the repr is traditional rather than + # stylized + idx = Index(["a", "b"]) + res = eval(repr(idx)) + tm.assert_index_equal(res, idx) + @pytest.mark.parametrize( "index,expected", [ diff --git a/pandas/tests/indexes/categorical/test_category.py b/pandas/tests/indexes/categorical/test_category.py index 87facbf529411..7af4f6809ec64 100644 --- a/pandas/tests/indexes/categorical/test_category.py +++ b/pandas/tests/indexes/categorical/test_category.py @@ -257,12 +257,6 @@ def test_ensure_copied_data(self): result = CategoricalIndex(index.values, copy=False) assert result._data._codes is index._data._codes - def test_frame_repr(self): - df = pd.DataFrame({"A": [1, 2, 3]}, index=CategoricalIndex(["a", "b", "c"])) - result = repr(df) - expected = " A\na 1\nb 2\nc 3" - assert result == expected - class TestCategoricalIndex2: def test_view_i8(self): diff --git a/pandas/tests/indexes/datetimes/test_formats.py b/pandas/tests/indexes/datetimes/test_formats.py index a181c38e2102a..4bf8df986801b 100644 --- a/pandas/tests/indexes/datetimes/test_formats.py +++ b/pandas/tests/indexes/datetimes/test_formats.py @@ -271,37 +271,16 @@ def test_dti_summary(self): result = idx._summary() assert result == expected - def test_dti_business_repr(self): + @pytest.mark.parametrize("tz", [None, pytz.utc, dateutil.tz.tzutc()]) + @pytest.mark.parametrize("freq", ["B", "C"]) + def test_dti_business_repr_etc_smoke(self, tz, freq): # only really care that it works - repr(pd.bdate_range(datetime(2009, 1, 1), datetime(2010, 1, 1))) - - def test_dti_business_summary(self): - rng = pd.bdate_range(datetime(2009, 1, 1), datetime(2010, 1, 1)) - rng._summary() - rng[2:2]._summary() - - def test_dti_business_summary_pytz(self): - pd.bdate_range("1/1/2005", "1/1/2009", tz=pytz.utc)._summary() - - def test_dti_business_summary_dateutil(self): - pd.bdate_range("1/1/2005", "1/1/2009", tz=dateutil.tz.tzutc())._summary() - - def test_dti_custom_business_repr(self): - # only really care that it works - repr(pd.bdate_range(datetime(2009, 1, 1), datetime(2010, 1, 1), freq="C")) - - def test_dti_custom_business_summary(self): - rng = pd.bdate_range(datetime(2009, 1, 1), datetime(2010, 1, 1), freq="C") - rng._summary() - rng[2:2]._summary() - - def test_dti_custom_business_summary_pytz(self): - pd.bdate_range("1/1/2005", "1/1/2009", freq="C", tz=pytz.utc)._summary() - - def test_dti_custom_business_summary_dateutil(self): - pd.bdate_range( - "1/1/2005", "1/1/2009", freq="C", tz=dateutil.tz.tzutc() - )._summary() + dti = pd.bdate_range( + datetime(2009, 1, 1), datetime(2010, 1, 1), tz=tz, freq=freq + ) + repr(dti) + dti._summary() + dti[2:2]._summary() class TestFormat: diff --git a/pandas/tests/indexes/datetimes/test_ops.py b/pandas/tests/indexes/datetimes/test_ops.py index 30c510864ce68..5db0aa5cf510f 100644 --- a/pandas/tests/indexes/datetimes/test_ops.py +++ b/pandas/tests/indexes/datetimes/test_ops.py @@ -37,7 +37,6 @@ def test_comparison(self, rng): def test_copy(self, rng): cp = rng.copy() - repr(cp) tm.assert_index_equal(cp, rng) def test_identical(self, rng): diff --git a/pandas/tests/indexes/interval/test_formats.py b/pandas/tests/indexes/interval/test_formats.py index d080516917892..bf335d154e186 100644 --- a/pandas/tests/indexes/interval/test_formats.py +++ b/pandas/tests/indexes/interval/test_formats.py @@ -14,15 +14,7 @@ class TestIntervalIndexRendering: - def test_frame_repr(self): - # https://github.com/pandas-dev/pandas/pull/24134/files - df = DataFrame( - {"A": [1, 2, 3, 4]}, index=IntervalIndex.from_breaks([0, 1, 2, 3, 4]) - ) - result = repr(df) - expected = " A\n(0, 1] 1\n(1, 2] 2\n(2, 3] 3\n(3, 4] 4" - assert result == expected - + # TODO: this is a test for DataFrame/Series, not IntervalIndex @pytest.mark.parametrize( "constructor,expected", [ diff --git a/pandas/tests/indexes/multi/test_integrity.py b/pandas/tests/indexes/multi/test_integrity.py index 45dd484eff4c6..26ef732635d1c 100644 --- a/pandas/tests/indexes/multi/test_integrity.py +++ b/pandas/tests/indexes/multi/test_integrity.py @@ -241,7 +241,6 @@ def test_rangeindex_fallback_coercion_bug(): ) df.index.names = ["fizz", "buzz"] - str(df) expected = pd.DataFrame( {"df2": np.arange(100), "df1": np.arange(100)}, index=MultiIndex.from_product([range(10), range(10)], names=["fizz", "buzz"]), diff --git a/pandas/tests/indexes/period/test_formats.py b/pandas/tests/indexes/period/test_formats.py index 888d814ac7eea..81c79f7d18f2f 100644 --- a/pandas/tests/indexes/period/test_formats.py +++ b/pandas/tests/indexes/period/test_formats.py @@ -65,12 +65,6 @@ def test_format_empty(self): with tm.assert_produces_warning(FutureWarning, match=msg): assert empty_idx.format(name=True) == [""] - def test_frame_repr(self): - df = pd.DataFrame({"A": [1, 2, 3]}, index=pd.date_range("2000", periods=3)) - result = repr(df) - expected = " A\n2000-01-01 1\n2000-01-02 2\n2000-01-03 3" - assert result == expected - @pytest.mark.parametrize("method", ["__repr__", "__str__"]) def test_representation(self, method): # GH#7601 @@ -118,6 +112,7 @@ def test_representation(self, method): result = getattr(idx, method)() assert result == expected + # TODO: These are Series.__repr__ tests def test_representation_to_series(self): # GH#10971 idx1 = PeriodIndex([], freq="D") diff --git a/pandas/tests/indexes/ranges/test_range.py b/pandas/tests/indexes/ranges/test_range.py index 95756b04bca69..ffb2dac840198 100644 --- a/pandas/tests/indexes/ranges/test_range.py +++ b/pandas/tests/indexes/ranges/test_range.py @@ -247,6 +247,7 @@ def test_cache(self): df = pd.DataFrame({"a": range(10)}, index=idx) + # df.__repr__ should not populate index cache str(df) assert idx._cache == {} diff --git a/pandas/tests/indexes/timedeltas/test_formats.py b/pandas/tests/indexes/timedeltas/test_formats.py index ee090bd0aaf0a..607336060cbbc 100644 --- a/pandas/tests/indexes/timedeltas/test_formats.py +++ b/pandas/tests/indexes/timedeltas/test_formats.py @@ -51,6 +51,7 @@ def test_representation(self, method): result = getattr(idx, method)() assert result == expected + # TODO: this is a Series.__repr__ test def test_representation_to_series(self): idx1 = TimedeltaIndex([], freq="D") idx2 = TimedeltaIndex(["1 days"], freq="D") diff --git a/pandas/tests/indexes/timedeltas/test_join.py b/pandas/tests/indexes/timedeltas/test_join.py index f3b12aa22bab0..89579d0c86f20 100644 --- a/pandas/tests/indexes/timedeltas/test_join.py +++ b/pandas/tests/indexes/timedeltas/test_join.py @@ -34,7 +34,6 @@ def test_does_not_convert_mixed_integer(self): r_idx_type="i", c_idx_type="td", ) - str(df) cols = df.columns.join(df.index, how="outer") joined = cols.join(df.columns) diff --git a/pandas/tests/indexing/multiindex/test_chaining_and_caching.py b/pandas/tests/indexing/multiindex/test_chaining_and_caching.py index c3a2c582854f3..2914bf4a3be05 100644 --- a/pandas/tests/indexing/multiindex/test_chaining_and_caching.py +++ b/pandas/tests/indexing/multiindex/test_chaining_and_caching.py @@ -75,10 +75,9 @@ def test_indexer_caching(): # make sure that indexers are in the _internal_names_set n = 1000001 index = MultiIndex.from_arrays([np.arange(n), np.arange(n)]) - s = Series(np.zeros(n), index=index) - str(s) + ser = Series(np.zeros(n), index=index) # setitem expected = Series(np.ones(n), index=index) - s[s == 0] = 1 - tm.assert_series_equal(s, expected) + ser[ser == 0] = 1 + tm.assert_series_equal(ser, expected) diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py index 562638f7058c6..6d70a6c59aa6b 100644 --- a/pandas/tests/indexing/test_chaining_and_caching.py +++ b/pandas/tests/indexing/test_chaining_and_caching.py @@ -44,9 +44,6 @@ def test_slice_consolidate_invalidate_item_cache(self, using_copy_on_write): # caches a reference to the 'bb' series df["bb"] - # repr machinery triggers consolidation - repr(df) - # Assignment to wrong series if using_copy_on_write: with tm.raises_chained_assignment_error(): diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index bc7604330695f..558ad7ded5619 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -229,17 +229,12 @@ def test_iloc_exceeds_bounds(self): tm.assert_series_equal(result, expected) # doc example - def check(result, expected): - str(result) - result.dtypes - tm.assert_frame_equal(result, expected) - dfl = DataFrame( np.random.default_rng(2).standard_normal((5, 2)), columns=list("AB") ) - check(dfl.iloc[:, 2:3], DataFrame(index=dfl.index, columns=[])) - check(dfl.iloc[:, 1:3], dfl.iloc[:, [1]]) - check(dfl.iloc[4:6], dfl.iloc[[4]]) + tm.assert_frame_equal(dfl.iloc[:, 2:3], DataFrame(index=dfl.index, columns=[])) + tm.assert_frame_equal(dfl.iloc[:, 1:3], dfl.iloc[:, [1]]) + tm.assert_frame_equal(dfl.iloc[4:6], dfl.iloc[[4]]) msg = "positional indexers are out-of-bounds" with pytest.raises(IndexError, match=msg): @@ -644,8 +639,6 @@ def test_iloc_getitem_doc_issue(self, using_array_manager): df.describe() result = df.iloc[3:5, 0:2] - str(result) - result.dtypes expected = DataFrame(arr[3:5, 0:2], index=index[3:5], columns=columns[0:2]) tm.assert_frame_equal(result, expected) @@ -653,8 +646,6 @@ def test_iloc_getitem_doc_issue(self, using_array_manager): # for dups df.columns = list("aaaa") result = df.iloc[3:5, 0:2] - str(result) - result.dtypes expected = DataFrame(arr[3:5, 0:2], index=index[3:5], columns=list("aa")) tm.assert_frame_equal(result, expected) @@ -668,8 +659,6 @@ def test_iloc_getitem_doc_issue(self, using_array_manager): if not using_array_manager: df._mgr.blocks[0].mgr_locs result = df.iloc[1:5, 2:4] - str(result) - result.dtypes expected = DataFrame(arr[1:5, 2:4], index=index[1:5], columns=columns[2:4]) tm.assert_frame_equal(result, expected) @@ -795,8 +784,8 @@ def test_iloc_mask(self): else: accessor = df answer = str(bin(accessor[mask]["nums"].sum())) - except (ValueError, IndexingError, NotImplementedError) as e: - answer = str(e) + except (ValueError, IndexingError, NotImplementedError) as err: + answer = str(err) key = ( idx, diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index 54e204c43dadd..dfbf30d06e82c 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -250,8 +250,6 @@ def test_dups_fancy_indexing(self): def test_dups_fancy_indexing_across_dtypes(self): # across dtypes df = DataFrame([[1, 2, 1.0, 2.0, 3.0, "foo", "bar"]], columns=list("aaaaaaa")) - df.head() - str(df) result = DataFrame([[1, 2, 1.0, 2.0, 3.0, "foo", "bar"]]) result.columns = list("aaaaaaa") # GH#3468 diff --git a/pandas/tests/indexing/test_partial.py b/pandas/tests/indexing/test_partial.py index 8f499644f1013..d4004ade02318 100644 --- a/pandas/tests/indexing/test_partial.py +++ b/pandas/tests/indexing/test_partial.py @@ -147,14 +147,10 @@ def test_partial_set_empty_frame_no_index(self): df = DataFrame(columns=["A", "B"]) df[0] = Series(1, index=range(4)) - df.dtypes - str(df) tm.assert_frame_equal(df, expected) df = DataFrame(columns=["A", "B"]) df.loc[:, 0] = Series(1, index=range(4)) - df.dtypes - str(df) tm.assert_frame_equal(df, expected) def test_partial_set_empty_frame_row(self): diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index 8901eb99b7612..b3b718a81ccf5 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -226,38 +226,6 @@ def test_repr_chop_threshold_column_below(self): "3 40.0 0.000000e+00" ) - def test_repr_obeys_max_seq_limit(self): - with option_context("display.max_seq_items", 2000): - assert len(printing.pprint_thing(list(range(1000)))) > 1000 - - with option_context("display.max_seq_items", 5): - assert len(printing.pprint_thing(list(range(1000)))) < 100 - - with option_context("display.max_seq_items", 1): - assert len(printing.pprint_thing(list(range(1000)))) < 9 - - def test_repr_set(self): - assert printing.pprint_thing({1}) == "{1}" - - def test_repr_is_valid_construction_code(self): - # for the case of Index, where the repr is traditional rather than - # stylized - idx = Index(["a", "b"]) - res = eval("pd." + repr(idx)) - tm.assert_series_equal(Series(res), Series(idx)) - - def test_repr_should_return_str(self): - # https://docs.python.org/3/reference/datamodel.html#object.__repr__ - # "...The return value must be a string object." - - # (str on py2.x, str (unicode) on py3) - - data = [8, 5, 3, 5] - index1 = ["\u03c3", "\u03c4", "\u03c5", "\u03c6"] - cols = ["\u03c8"] - df = DataFrame(data, columns=cols, index=index1) - assert isinstance(df.__repr__(), str) - def test_repr_no_backslash(self): with option_context("mode.sim_interactive", True): df = DataFrame(np.random.default_rng(2).standard_normal((10, 4))) @@ -913,6 +881,7 @@ def test_truncate_with_different_dtypes(self): result = str(s) assert "object" in result + def test_truncate_with_different_dtypes2(self): # 12045 df = DataFrame({"text": ["some words"] + [None] * 9}) @@ -1401,14 +1370,6 @@ def gen_series_formatting(): class TestSeriesFormatting: - def test_repr_unicode(self): - s = Series(["\u03c3"] * 10) - repr(s) - - a = Series(["\u05d0"] * 1000) - a.name = "title1" - repr(a) - def test_freq_name_separation(self): s = Series( np.random.default_rng(2).standard_normal(10), diff --git a/pandas/tests/io/formats/test_printing.py b/pandas/tests/io/formats/test_printing.py index e2b65b1fdc40a..acf2bc72c687d 100644 --- a/pandas/tests/io/formats/test_printing.py +++ b/pandas/tests/io/formats/test_printing.py @@ -16,17 +16,31 @@ def test_adjoin(): assert adjoined == expected -def test_repr_binary_type(): - letters = string.ascii_letters - try: - raw = bytes(letters, encoding=cf.get_option("display.encoding")) - except TypeError: - raw = bytes(letters) - b = str(raw.decode("utf-8")) - res = printing.pprint_thing(b, quote_strings=True) - assert res == repr(b) - res = printing.pprint_thing(b, quote_strings=False) - assert res == b +class TestPPrintThing: + def test_repr_binary_type(self): + letters = string.ascii_letters + try: + raw = bytes(letters, encoding=cf.get_option("display.encoding")) + except TypeError: + raw = bytes(letters) + b = str(raw.decode("utf-8")) + res = printing.pprint_thing(b, quote_strings=True) + assert res == repr(b) + res = printing.pprint_thing(b, quote_strings=False) + assert res == b + + def test_repr_obeys_max_seq_limit(self): + with cf.option_context("display.max_seq_items", 2000): + assert len(printing.pprint_thing(list(range(1000)))) > 1000 + + with cf.option_context("display.max_seq_items", 5): + assert len(printing.pprint_thing(list(range(1000)))) < 100 + + with cf.option_context("display.max_seq_items", 1): + assert len(printing.pprint_thing(list(range(1000)))) < 9 + + def test_repr_set(self): + assert printing.pprint_thing({1}) == "{1}" class TestFormatBase: diff --git a/pandas/tests/io/parser/test_parse_dates.py b/pandas/tests/io/parser/test_parse_dates.py index d546d1275441d..2fd389772ca4f 100644 --- a/pandas/tests/io/parser/test_parse_dates.py +++ b/pandas/tests/io/parser/test_parse_dates.py @@ -1891,8 +1891,8 @@ def _helper_hypothesis_delimited_date(call, date_string, **kwargs): msg, result = None, None try: result = call(date_string, **kwargs) - except ValueError as er: - msg = str(er) + except ValueError as err: + msg = str(err) return msg, result diff --git a/pandas/tests/reshape/test_crosstab.py b/pandas/tests/reshape/test_crosstab.py index 2b6ebded3d325..c0e9b266b0d06 100644 --- a/pandas/tests/reshape/test_crosstab.py +++ b/pandas/tests/reshape/test_crosstab.py @@ -887,7 +887,4 @@ def test_categoricals(a_dtype, b_dtype): if not a_is_cat: expected = expected.loc[[0, 2, "All"]] expected["All"] = expected["All"].astype("int64") - repr(result) - repr(expected) - repr(expected.loc[[0, 2, "All"]]) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index 2d41b6d355ead..1f97d7cb605cf 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -2497,7 +2497,6 @@ def test_pivot_integer_bug(self): df = DataFrame(data=[("A", "1", "A1"), ("B", "2", "B2")]) result = df.pivot(index=1, columns=0, values=2) - repr(result) tm.assert_index_equal(result.columns, Index(["A", "B"], name=0)) def test_pivot_index_none(self): diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 8d9b46508a25f..195c50969ffae 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -412,8 +412,6 @@ def test_constructor_categorical_with_coercion(self): s = Series(factor, name="A") assert s.dtype == "category" assert len(s) == len(factor) - str(s.values) - str(s) # in a frame df = DataFrame({"A": factor}) @@ -422,15 +420,11 @@ def test_constructor_categorical_with_coercion(self): result = df.iloc[:, 0] tm.assert_series_equal(result, s) assert len(df) == len(factor) - str(df.values) - str(df) df = DataFrame({"A": s}) result = df["A"] tm.assert_series_equal(result, s) assert len(df) == len(factor) - str(df.values) - str(df) # multiples df = DataFrame({"A": s, "B": s, "C": 1}) @@ -440,8 +434,6 @@ def test_constructor_categorical_with_coercion(self): tm.assert_series_equal(result2, s, check_names=False) assert result2.name == "B" assert len(df) == len(factor) - str(df.values) - str(df) def test_constructor_categorical_with_coercion2(self): # GH8623 diff --git a/pandas/tests/series/test_repr.py b/pandas/tests/series/test_repr.py index 86addb9dadfad..17b28b7f1ab57 100644 --- a/pandas/tests/series/test_repr.py +++ b/pandas/tests/series/test_repr.py @@ -160,11 +160,6 @@ def test_empty_int64(self, name, expected): s = Series([], dtype=np.int64, name=name) assert repr(s) == expected - def test_tidy_repr(self): - a = Series(["\u05d0"] * 1000) - a.name = "title1" - repr(a) # should not raise exception - def test_repr_bool_fails(self, capsys): s = Series( [ @@ -188,17 +183,6 @@ def test_repr_name_iterable_indexable(self): s.name = ("\u05d0",) * 2 repr(s) - def test_repr_should_return_str(self): - # https://docs.python.org/3/reference/datamodel.html#object.__repr__ - # ...The return value must be a string object. - - # (str on py2.x, str (unicode) on py3) - - data = [8, 5, 3, 5] - index1 = ["\u03c3", "\u03c4", "\u03c5", "\u03c6"] - df = Series(data, index=index1) - assert type(df.__repr__() == str) # both py2 / 3 - def test_repr_max_rows(self): # GH 6863 with option_context("display.max_rows", None): @@ -208,6 +192,13 @@ def test_unicode_string_with_unicode(self): df = Series(["\u05d0"], name="\u05d1") str(df) + ser = Series(["\u03c3"] * 10) + repr(ser) + + ser2 = Series(["\u05d0"] * 1000) + ser2.name = "title1" + repr(ser2) + def test_str_to_bytes_raises(self): # GH 26447 df = Series(["abc"], name="abc")