Skip to content

Commit 055690e

Browse files
committed
updated options_context and simplified dictionary handling in set_option
1 parent 2263ba3 commit 055690e

File tree

2 files changed

+37
-14
lines changed

2 files changed

+37
-14
lines changed

pandas/_config/config.py

Lines changed: 9 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -264,18 +264,7 @@ def set_option(*args) -> None:
264264
"""
265265
# Handle dictionary input
266266
if len(args) == 1 and isinstance(args[0], dict):
267-
options_dict = args[0]
268-
for k, v in options_dict.items():
269-
key = _get_single_key(k)
270-
opt = _get_registered_option(key)
271-
if opt and opt.validator:
272-
opt.validator(v)
273-
# walk the nested dict
274-
root, k_root = _get_root(key)
275-
root[k_root] = v
276-
if opt.cb:
277-
opt.cb(key)
278-
return
267+
args = tuple(kv for item in args[0].items() for kv in item)
279268

280269
# Handle single option-value pair
281270
if len(args) == 2:
@@ -485,9 +474,10 @@ def option_context(*args) -> Generator[None]:
485474
486475
Parameters
487476
----------
488-
*args : str | object
477+
*args : str | object | dict
489478
An even amount of arguments provided in pairs which will be
490-
interpreted as (pattern, value) pairs.
479+
interpreted as (pattern, value) pairs. Alternatively, a single
480+
dictionary of {pattern: value} may be provided.
491481
492482
Returns
493483
-------
@@ -516,7 +506,12 @@ def option_context(*args) -> Generator[None]:
516506
>>> from pandas import option_context
517507
>>> with option_context("display.max_rows", 10, "display.max_columns", 5):
518508
... pass
509+
>>> with option_context({"display.max_rows": 10, "display.max_columns": 5}):
510+
... pass
519511
"""
512+
if len(args) == 1 and isinstance(args[0], dict):
513+
args = tuple(kv for item in args[0].items() for kv in item)
514+
520515
if len(args) % 2 != 0 or len(args) < 2:
521516
raise ValueError(
522517
"Provide an even amount of arguments as "

pandas/tests/config/test_config.py

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -395,6 +395,34 @@ def f():
395395

396396
f()
397397

398+
def test_set_ContextManager_dict(self):
399+
def eq(val):
400+
assert cf.get_option("a") == val
401+
assert cf.get_option("b.c") == val
402+
403+
cf.register_option("a", 0)
404+
cf.register_option("b.c", 0)
405+
406+
eq(0)
407+
with cf.option_context({"a": 15, "b.c": 15}):
408+
eq(15)
409+
with cf.option_context({"a": 25, "b.c": 25}):
410+
eq(25)
411+
eq(15)
412+
eq(0)
413+
414+
cf.set_option("a", 17)
415+
cf.set_option("b.c", 17)
416+
eq(17)
417+
418+
# Test that option_context can be used as a decorator too
419+
@cf.option_context({"a": 123, "b.c": 123})
420+
def f():
421+
eq(123)
422+
423+
f()
424+
425+
398426
def test_attribute_access(self):
399427
holder = []
400428

0 commit comments

Comments
 (0)