diff --git a/pandas/tests/indexes/multi/test_formats.py b/pandas/tests/indexes/multi/test_formats.py index a6dadd42f7bf0..f71472b726fa2 100644 --- a/pandas/tests/indexes/multi/test_formats.py +++ b/pandas/tests/indexes/multi/test_formats.py @@ -8,7 +8,6 @@ Index, MultiIndex, ) -import pandas._testing as tm def test_format(idx): @@ -27,13 +26,10 @@ def test_format_sparse_config(idx): warn_filters = warnings.filters warnings.filterwarnings("ignore", category=FutureWarning, module=".*format") # GH1538 - pd.set_option("display.multi_sparse", False) - - result = idx.format() + with pd.option_context("display.multi_sparse", False): + result = idx.format() assert result[1] == "foo two" - tm.reset_display_options() - warnings.filters = warn_filters diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py index 4fb90a2d95ac9..c8837a617bd9a 100644 --- a/pandas/tests/indexing/test_chaining_and_caching.py +++ b/pandas/tests/indexing/test_chaining_and_caching.py @@ -157,16 +157,17 @@ def test_setitem_chained_setfault(self): @pytest.mark.arm_slow def test_detect_chained_assignment(self): - pd.set_option("chained_assignment", "raise") - - # work with the chain - expected = DataFrame([[-5, 1], [-6, 3]], columns=list("AB")) - df = DataFrame(np.arange(4).reshape(2, 2), columns=list("AB"), dtype="int64") - assert df._is_copy is None + with option_context("chained_assignment", "raise"): + # work with the chain + expected = DataFrame([[-5, 1], [-6, 3]], columns=list("AB")) + df = DataFrame( + np.arange(4).reshape(2, 2), columns=list("AB"), dtype="int64" + ) + assert df._is_copy is None - df["A"][0] = -5 - df["A"][1] = -6 - tm.assert_frame_equal(df, expected) + df["A"][0] = -5 + df["A"][1] = -6 + tm.assert_frame_equal(df, expected) @pytest.mark.arm_slow def test_detect_chained_assignment_raises(self, using_array_manager): diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py index 0315783569c23..6f06ef9c09e52 100644 --- a/pandas/tests/io/excel/test_writers.py +++ b/pandas/tests/io/excel/test_writers.py @@ -18,8 +18,7 @@ DataFrame, Index, MultiIndex, - get_option, - set_option, + option_context, ) import pandas._testing as tm @@ -53,10 +52,8 @@ def set_engine(engine, ext): the test it rolls back said change to the global option. """ option_name = f"io.excel.{ext.strip('.')}.writer" - prev_engine = get_option(option_name) - set_option(option_name, engine) - yield - set_option(option_name, prev_engine) # Roll back option change + with option_context(option_name, engine): + yield @pytest.mark.parametrize( @@ -1294,7 +1291,7 @@ def check_called(func): del called_save[:] del called_write_cells[:] - with pd.option_context("io.excel.xlsx.writer", "dummy"): + with option_context("io.excel.xlsx.writer", "dummy"): path = "something.xlsx" with tm.ensure_clean(path) as filepath: register_writer(DummyClass) diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index 801bb1845e01e..99378654c6c11 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -1146,20 +1146,18 @@ def test_wide_repr(self): ): max_cols = get_option("display.max_columns") df = DataFrame(tm.rands_array(25, size=(10, max_cols - 1))) - set_option("display.expand_frame_repr", False) - rep_str = repr(df) + with option_context("display.expand_frame_repr", False): + rep_str = repr(df) assert f"10 rows x {max_cols - 1} columns" in rep_str - set_option("display.expand_frame_repr", True) - wide_repr = repr(df) + with option_context("display.expand_frame_repr", True): + wide_repr = repr(df) assert rep_str != wide_repr with option_context("display.width", 120): wider_repr = repr(df) assert len(wider_repr) < len(wide_repr) - reset_option("display.expand_frame_repr") - def test_wide_repr_wide_columns(self): with option_context("mode.sim_interactive", True, "display.max_columns", 20): df = DataFrame( @@ -1174,11 +1172,10 @@ def test_wide_repr_named(self): max_cols = get_option("display.max_columns") df = DataFrame(tm.rands_array(25, size=(10, max_cols - 1))) df.index.name = "DataFrame Index" - set_option("display.expand_frame_repr", False) - - rep_str = repr(df) - set_option("display.expand_frame_repr", True) - wide_repr = repr(df) + with option_context("display.expand_frame_repr", False): + rep_str = repr(df) + with option_context("display.expand_frame_repr", True): + wide_repr = repr(df) assert rep_str != wide_repr with option_context("display.width", 150): @@ -1188,18 +1185,16 @@ def test_wide_repr_named(self): for line in wide_repr.splitlines()[1::13]: assert "DataFrame Index" in line - reset_option("display.expand_frame_repr") - def test_wide_repr_multiindex(self): with option_context("mode.sim_interactive", True, "display.max_columns", 20): midx = MultiIndex.from_arrays(tm.rands_array(5, size=(2, 10))) max_cols = get_option("display.max_columns") df = DataFrame(tm.rands_array(25, size=(10, max_cols - 1)), index=midx) df.index.names = ["Level 0", "Level 1"] - set_option("display.expand_frame_repr", False) - rep_str = repr(df) - set_option("display.expand_frame_repr", True) - wide_repr = repr(df) + with option_context("display.expand_frame_repr", False): + rep_str = repr(df) + with option_context("display.expand_frame_repr", True): + wide_repr = repr(df) assert rep_str != wide_repr with option_context("display.width", 150): @@ -1209,8 +1204,6 @@ def test_wide_repr_multiindex(self): for line in wide_repr.splitlines()[1::13]: assert "Level 0 Level 1" in line - reset_option("display.expand_frame_repr") - def test_wide_repr_multiindex_cols(self): with option_context("mode.sim_interactive", True, "display.max_columns", 20): max_cols = get_option("display.max_columns") @@ -1220,34 +1213,30 @@ def test_wide_repr_multiindex_cols(self): tm.rands_array(25, (10, max_cols - 1)), index=midx, columns=mcols ) df.index.names = ["Level 0", "Level 1"] - set_option("display.expand_frame_repr", False) - rep_str = repr(df) - set_option("display.expand_frame_repr", True) - wide_repr = repr(df) + with option_context("display.expand_frame_repr", False): + rep_str = repr(df) + with option_context("display.expand_frame_repr", True): + wide_repr = repr(df) assert rep_str != wide_repr with option_context("display.width", 150, "display.max_columns", 20): wider_repr = repr(df) assert len(wider_repr) < len(wide_repr) - reset_option("display.expand_frame_repr") - def test_wide_repr_unicode(self): with option_context("mode.sim_interactive", True, "display.max_columns", 20): max_cols = 20 df = DataFrame(tm.rands_array(25, size=(10, max_cols - 1))) - set_option("display.expand_frame_repr", False) - rep_str = repr(df) - set_option("display.expand_frame_repr", True) - wide_repr = repr(df) + with option_context("display.expand_frame_repr", False): + rep_str = repr(df) + with option_context("display.expand_frame_repr", True): + wide_repr = repr(df) assert rep_str != wide_repr with option_context("display.width", 150): wider_repr = repr(df) assert len(wider_repr) < len(wide_repr) - reset_option("display.expand_frame_repr") - def test_wide_repr_wide_long_columns(self): with option_context("mode.sim_interactive", True): df = DataFrame({"a": ["a" * 30, "b" * 30], "b": ["c" * 70, "d" * 80]}) diff --git a/pandas/tests/io/pytables/test_append.py b/pandas/tests/io/pytables/test_append.py index 5544b8112627b..784f1aa94d0ee 100644 --- a/pandas/tests/io/pytables/test_append.py +++ b/pandas/tests/io/pytables/test_append.py @@ -214,66 +214,66 @@ def test_append_all_nans(setup_path): tm.assert_frame_equal(store["df2"], df) # tests the option io.hdf.dropna_table - pd.set_option("io.hdf.dropna_table", False) - _maybe_remove(store, "df3") - store.append("df3", df[:10]) - store.append("df3", df[10:]) - tm.assert_frame_equal(store["df3"], df) + with pd.option_context("io.hdf.dropna_table", False): + _maybe_remove(store, "df3") + store.append("df3", df[:10]) + store.append("df3", df[10:]) + tm.assert_frame_equal(store["df3"], df) - pd.set_option("io.hdf.dropna_table", True) - _maybe_remove(store, "df4") - store.append("df4", df[:10]) - store.append("df4", df[10:]) - tm.assert_frame_equal(store["df4"], df[-4:]) + with pd.option_context("io.hdf.dropna_table", True): + _maybe_remove(store, "df4") + store.append("df4", df[:10]) + store.append("df4", df[10:]) + tm.assert_frame_equal(store["df4"], df[-4:]) - # nan some entire rows (string are still written!) - df = DataFrame( - { - "A1": np.random.randn(20), - "A2": np.random.randn(20), - "B": "foo", - "C": "bar", - }, - index=np.arange(20), - ) + # nan some entire rows (string are still written!) + df = DataFrame( + { + "A1": np.random.randn(20), + "A2": np.random.randn(20), + "B": "foo", + "C": "bar", + }, + index=np.arange(20), + ) - df.loc[0:15, :] = np.nan + df.loc[0:15, :] = np.nan - _maybe_remove(store, "df") - store.append("df", df[:10], dropna=True) - store.append("df", df[10:], dropna=True) - tm.assert_frame_equal(store["df"], df) + _maybe_remove(store, "df") + store.append("df", df[:10], dropna=True) + store.append("df", df[10:], dropna=True) + tm.assert_frame_equal(store["df"], df) - _maybe_remove(store, "df2") - store.append("df2", df[:10], dropna=False) - store.append("df2", df[10:], dropna=False) - tm.assert_frame_equal(store["df2"], df) + _maybe_remove(store, "df2") + store.append("df2", df[:10], dropna=False) + store.append("df2", df[10:], dropna=False) + tm.assert_frame_equal(store["df2"], df) - # nan some entire rows (but since we have dates they are still - # written!) - df = DataFrame( - { - "A1": np.random.randn(20), - "A2": np.random.randn(20), - "B": "foo", - "C": "bar", - "D": Timestamp("20010101"), - "E": datetime.datetime(2001, 1, 2, 0, 0), - }, - index=np.arange(20), - ) + # nan some entire rows (but since we have dates they are still + # written!) + df = DataFrame( + { + "A1": np.random.randn(20), + "A2": np.random.randn(20), + "B": "foo", + "C": "bar", + "D": Timestamp("20010101"), + "E": datetime.datetime(2001, 1, 2, 0, 0), + }, + index=np.arange(20), + ) - df.loc[0:15, :] = np.nan + df.loc[0:15, :] = np.nan - _maybe_remove(store, "df") - store.append("df", df[:10], dropna=True) - store.append("df", df[10:], dropna=True) - tm.assert_frame_equal(store["df"], df) + _maybe_remove(store, "df") + store.append("df", df[:10], dropna=True) + store.append("df", df[10:], dropna=True) + tm.assert_frame_equal(store["df"], df) - _maybe_remove(store, "df2") - store.append("df2", df[:10], dropna=False) - store.append("df2", df[10:], dropna=False) - tm.assert_frame_equal(store["df2"], df) + _maybe_remove(store, "df2") + store.append("df2", df[:10], dropna=False) + store.append("df2", df[10:], dropna=False) + tm.assert_frame_equal(store["df2"], df) def test_append_frame_column_oriented(setup_path): @@ -898,8 +898,9 @@ def test_append_to_multiple_dropna_false(setup_path): df1.iloc[1, df1.columns.get_indexer(["A", "B"])] = np.nan df = concat([df1, df2], axis=1) - with ensure_clean_store(setup_path) as store: - + with ensure_clean_store(setup_path) as store, pd.option_context( + "io.hdf.dropna_table", True + ): # dropna=False shouldn't synchronize row indexes store.append_to_multiple( {"df1a": ["A", "B"], "df2a": None}, df, selector="df1a", dropna=False diff --git a/pandas/tests/io/pytables/test_put.py b/pandas/tests/io/pytables/test_put.py index 8e7b31bcf8bca..139c509505022 100644 --- a/pandas/tests/io/pytables/test_put.py +++ b/pandas/tests/io/pytables/test_put.py @@ -59,46 +59,41 @@ def test_api_default_format(setup_path): with ensure_clean_store(setup_path) as store: df = tm.makeDataFrame() - pd.set_option("io.hdf.default_format", "fixed") - _maybe_remove(store, "df") - store.put("df", df) - assert not store.get_storer("df").is_table + with pd.option_context("io.hdf.default_format", "fixed"): + _maybe_remove(store, "df") + store.put("df", df) + assert not store.get_storer("df").is_table - msg = "Can only append to Tables" + msg = "Can only append to Tables" + with pytest.raises(ValueError, match=msg): + store.append("df2", df) - with pytest.raises(ValueError, match=msg): - store.append("df2", df) - - pd.set_option("io.hdf.default_format", "table") - _maybe_remove(store, "df") - store.put("df", df) - assert store.get_storer("df").is_table - _maybe_remove(store, "df2") - store.append("df2", df) - assert store.get_storer("df").is_table + with pd.option_context("io.hdf.default_format", "table"): + _maybe_remove(store, "df") + store.put("df", df) + assert store.get_storer("df").is_table - pd.set_option("io.hdf.default_format", None) + _maybe_remove(store, "df2") + store.append("df2", df) + assert store.get_storer("df").is_table with ensure_clean_path(setup_path) as path: - df = tm.makeDataFrame() - pd.set_option("io.hdf.default_format", "fixed") - df.to_hdf(path, "df") - with HDFStore(path) as store: - assert not store.get_storer("df").is_table - with pytest.raises(ValueError, match=msg): - df.to_hdf(path, "df2", append=True) - - pd.set_option("io.hdf.default_format", "table") - df.to_hdf(path, "df3") - with HDFStore(path) as store: - assert store.get_storer("df3").is_table - df.to_hdf(path, "df4", append=True) - with HDFStore(path) as store: - assert store.get_storer("df4").is_table - - pd.set_option("io.hdf.default_format", None) + with pd.option_context("io.hdf.default_format", "fixed"): + df.to_hdf(path, "df") + with HDFStore(path) as store: + assert not store.get_storer("df").is_table + with pytest.raises(ValueError, match=msg): + df.to_hdf(path, "df2", append=True) + + with pd.option_context("io.hdf.default_format", "table"): + df.to_hdf(path, "df3") + with HDFStore(path) as store: + assert store.get_storer("df3").is_table + df.to_hdf(path, "df4", append=True) + with HDFStore(path) as store: + assert store.get_storer("df4").is_table def test_put(setup_path): diff --git a/pandas/tests/plotting/test_backend.py b/pandas/tests/plotting/test_backend.py index be053a8f46051..1e3635714b745 100644 --- a/pandas/tests/plotting/test_backend.py +++ b/pandas/tests/plotting/test_backend.py @@ -18,9 +18,8 @@ @pytest.fixture def restore_backend(): """Restore the plotting backend to matplotlib""" - pandas.set_option("plotting.backend", "matplotlib") - yield - pandas.set_option("plotting.backend", "matplotlib") + with pandas.option_context("plotting.backend", "matplotlib"): + yield def test_backend_is_not_module(): diff --git a/pandas/tests/test_expressions.py b/pandas/tests/test_expressions.py index d8afb4ab83dfd..495fd637d01fe 100644 --- a/pandas/tests/test_expressions.py +++ b/pandas/tests/test_expressions.py @@ -5,7 +5,7 @@ import numpy as np import pytest -from pandas import set_option +from pandas import option_context import pandas._testing as tm from pandas.core.api import ( DataFrame, @@ -61,9 +61,8 @@ def call_op(df, other, flex: bool, opname: str): else: op = getattr(operator, opname) - set_option("compute.use_numexpr", False) - expected = op(df, other) - set_option("compute.use_numexpr", True) + with option_context("compute.use_numexpr", False): + expected = op(df, other) expr.get_test_result() @@ -122,9 +121,8 @@ def test_run_binary(self, df, flex, comparison_op): elsewhere. """ arith = comparison_op.__name__ - set_option("compute.use_numexpr", False) - other = df.copy() + 1 - set_option("compute.use_numexpr", True) + with option_context("compute.use_numexpr", False): + other = df.copy() + 1 expr._MIN_ELEMENTS = 0 expr.set_test_mode(True) @@ -184,9 +182,9 @@ def testit(): result = expr._can_use_numexpr(op, op_str, right, right, "evaluate") assert not result - set_option("compute.use_numexpr", False) - testit() - set_option("compute.use_numexpr", True) + with option_context("compute.use_numexpr", False): + testit() + expr.set_numexpr_threads(1) testit() expr.set_numexpr_threads() @@ -220,9 +218,9 @@ def testit(): result = expr._can_use_numexpr(op, op_str, right, f22, "evaluate") assert not result - set_option("compute.use_numexpr", False) - testit() - set_option("compute.use_numexpr", True) + with option_context("compute.use_numexpr", False): + testit() + expr.set_numexpr_threads(1) testit() expr.set_numexpr_threads() @@ -238,9 +236,9 @@ def testit(): expected = np.where(c, df.values, df.values + 1) tm.assert_numpy_array_equal(result, expected) - set_option("compute.use_numexpr", False) - testit() - set_option("compute.use_numexpr", True) + with option_context("compute.use_numexpr", False): + testit() + expr.set_numexpr_threads(1) testit() expr.set_numexpr_threads() @@ -365,9 +363,8 @@ def test_frame_series_axis(self, axis, arith): op_func = getattr(df, arith) - set_option("compute.use_numexpr", False) - expected = op_func(other, axis=axis) - set_option("compute.use_numexpr", True) + with option_context("compute.use_numexpr", False): + expected = op_func(other, axis=axis) result = op_func(other, axis=axis) tm.assert_frame_equal(expected, result) @@ -392,9 +389,9 @@ def test_python_semantics_with_numexpr_installed(self, op, box, scalar): result = method(scalar) # compare result with numpy - set_option("compute.use_numexpr", False) - expected = method(scalar) - set_option("compute.use_numexpr", True) + with option_context("compute.use_numexpr", False): + expected = method(scalar) + tm.assert_equal(result, expected) # compare result element-wise with Python diff --git a/pandas/tests/test_nanops.py b/pandas/tests/test_nanops.py index ee451d0288581..fa95ff86cb6b9 100644 --- a/pandas/tests/test_nanops.py +++ b/pandas/tests/test_nanops.py @@ -1036,13 +1036,11 @@ def test_use_bottleneck(): if nanops._BOTTLENECK_INSTALLED: - pd.set_option("use_bottleneck", True) - assert pd.get_option("use_bottleneck") + with pd.option_context("use_bottleneck", True): + assert pd.get_option("use_bottleneck") - pd.set_option("use_bottleneck", False) - assert not pd.get_option("use_bottleneck") - - pd.set_option("use_bottleneck", use_bn) + with pd.option_context("use_bottleneck", False): + assert not pd.get_option("use_bottleneck") @pytest.mark.parametrize(