diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 3aa50ad609064..d299121092987 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -142,7 +142,7 @@ Bug Fixes - +- BUG: Option context applies on __enter__ (:issue:`8514`) diff --git a/pandas/core/config.py b/pandas/core/config.py index 60dc1d7d0341e..2c1865730874d 100644 --- a/pandas/core/config.py +++ b/pandas/core/config.py @@ -384,19 +384,18 @@ def __init__(self, *args): 'option_context(pat, val, [(pat, val), ...)).' ) - ops = list(zip(args[::2], args[1::2])) + self.ops = list(zip(args[::2], args[1::2])) + + def __enter__(self): undo = [] - for pat, val in ops: + for pat, val in self.ops: undo.append((pat, _get_option(pat, silent=True))) self.undo = undo - for pat, val in ops: + for pat, val in self.ops: _set_option(pat, val, silent=True) - def __enter__(self): - pass - def __exit__(self, *args): if self.undo: for pat, val in self.undo: diff --git a/pandas/tests/test_config.py b/pandas/tests/test_config.py index dc5e9a67bdb65..3a8fdd877f5a0 100644 --- a/pandas/tests/test_config.py +++ b/pandas/tests/test_config.py @@ -425,3 +425,24 @@ def f3(key): options.c = 1 self.assertEqual(len(holder), 1) + def test_option_context_scope(self): + # Ensure that creating a context does not affect the existing + # environment as it is supposed to be used with the `with` statement. + # See https://github.com/pydata/pandas/issues/8514 + + original_value = 60 + context_value = 10 + option_name = 'a' + + self.cf.register_option(option_name, original_value) + + # Ensure creating contexts didn't affect the current context. + ctx = self.cf.option_context(option_name, context_value) + self.assertEqual(self.cf.get_option(option_name), original_value) + + # Ensure the correct value is available inside the context. + with ctx: + self.assertEqual(self.cf.get_option(option_name), context_value) + + # Ensure the current context is reset + self.assertEqual(self.cf.get_option(option_name), original_value)