Skip to content

Commit f21539b

Browse files
committed
BUG: Option context applies on __enter__
Option context no longer overrides options when used outside a `with` statement. Added test TestConfig.test_option_config_scope Closes #8514
1 parent a3e478d commit f21539b

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
@@ -384,19 +384,18 @@ def __init__(self, *args):
384384
'option_context(pat, val, [(pat, val), ...)).'
385385
)
386386

387-
ops = list(zip(args[::2], args[1::2]))
387+
self.ops = list(zip(args[::2], args[1::2]))
388+
389+
def __enter__(self):
388390
undo = []
389-
for pat, val in ops:
391+
for pat, val in self.ops:
390392
undo.append((pat, _get_option(pat, silent=True)))
391393

392394
self.undo = undo
393395

394-
for pat, val in ops:
396+
for pat, val in self.ops:
395397
_set_option(pat, val, silent=True)
396398

397-
def __enter__(self):
398-
pass
399-
400399
def __exit__(self, *args):
401400
if self.undo:
402401
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)