Skip to content

Commit e9ee47c

Browse files
Merge pull request #8925 from hkleynhans/fix/8514_option_context_with
BUG: Option context applies on __enter__
2 parents 26129f5 + f21539b commit e9ee47c

File tree

3 files changed

+27
-7
lines changed

3 files changed

+27
-7
lines changed

doc/source/whatsnew/v0.15.2.txt

+1-1
Original file line numberDiff line numberDiff line change
@@ -142,7 +142,7 @@ Bug Fixes
142142

143143

144144

145-
145+
- BUG: Option context applies on __enter__ (:issue:`8514`)
146146

147147

148148

pandas/core/config.py

+5-6
Original file line numberDiff line numberDiff line change
@@ -385,19 +385,18 @@ def __init__(self, *args):
385385
'option_context(pat, val, [(pat, val), ...)).'
386386
)
387387

388-
ops = list(zip(args[::2], args[1::2]))
388+
self.ops = list(zip(args[::2], args[1::2]))
389+
390+
def __enter__(self):
389391
undo = []
390-
for pat, val in ops:
392+
for pat, val in self.ops:
391393
undo.append((pat, _get_option(pat, silent=True)))
392394

393395
self.undo = undo
394396

395-
for pat, val in ops:
397+
for pat, val in self.ops:
396398
_set_option(pat, val, silent=True)
397399

398-
def __enter__(self):
399-
pass
400-
401400
def __exit__(self, *args):
402401
if self.undo:
403402
for pat, val in self.undo:

pandas/tests/test_config.py

+21
Original file line numberDiff line numberDiff line change
@@ -425,3 +425,24 @@ def f3(key):
425425
options.c = 1
426426
self.assertEqual(len(holder), 1)
427427

428+
def test_option_context_scope(self):
429+
# Ensure that creating a context does not affect the existing
430+
# environment as it is supposed to be used with the `with` statement.
431+
# See https://github.com/pydata/pandas/issues/8514
432+
433+
original_value = 60
434+
context_value = 10
435+
option_name = 'a'
436+
437+
self.cf.register_option(option_name, original_value)
438+
439+
# Ensure creating contexts didn't affect the current context.
440+
ctx = self.cf.option_context(option_name, context_value)
441+
self.assertEqual(self.cf.get_option(option_name), original_value)
442+
443+
# Ensure the correct value is available inside the context.
444+
with ctx:
445+
self.assertEqual(self.cf.get_option(option_name), context_value)
446+
447+
# Ensure the current context is reset
448+
self.assertEqual(self.cf.get_option(option_name), original_value)

0 commit comments

Comments
 (0)