Context manager to temporarily set options in a ``with`` statement. This method allows users to set one or more pandas options temporarily within a controlled block. The previous options' values are restored once the block is exited. This is useful when making temporary adjustments
(*args)
| 452 | |
| 453 | @contextmanager |
| 454 | def option_context(*args) -> Generator[None]: |
| 455 | """ |
| 456 | Context manager to temporarily set options in a ``with`` statement. |
| 457 | |
| 458 | This method allows users to set one or more pandas options temporarily |
| 459 | within a controlled block. The previous options' values are restored |
| 460 | once the block is exited. This is useful when making temporary adjustments |
| 461 | to pandas' behavior without affecting the global state. |
| 462 | |
| 463 | Parameters |
| 464 | ---------- |
| 465 | *args : str | object | dict |
| 466 | An even amount of arguments provided in pairs which will be |
| 467 | interpreted as (pattern, value) pairs. Alternatively, a single |
| 468 | dictionary of {pattern: value} may be provided. |
| 469 | |
| 470 | Returns |
| 471 | ------- |
| 472 | None |
| 473 | No return value. |
| 474 | |
| 475 | Yields |
| 476 | ------ |
| 477 | None |
| 478 | No yield value. |
| 479 | |
| 480 | See Also |
| 481 | -------- |
| 482 | get_option : Retrieve the value of the specified option. |
| 483 | set_option : Set the value of the specified option. |
| 484 | reset_option : Reset one or more options to their default value. |
| 485 | describe_option : Print the description for one or more registered options. |
| 486 | |
| 487 | Notes |
| 488 | ----- |
| 489 | For all available options, please view the :ref:`User Guide <options.available>` |
| 490 | or use ``pandas.describe_option()``. |
| 491 | |
| 492 | Examples |
| 493 | -------- |
| 494 | >>> from pandas import option_context |
| 495 | >>> with option_context("display.max_rows", 10, "display.max_columns", 5): |
| 496 | ... pass |
| 497 | >>> with option_context({"display.max_rows": 10, "display.max_columns": 5}): |
| 498 | ... pass |
| 499 | """ |
| 500 | if len(args) == 1 and isinstance(args[0], dict): |
| 501 | args = tuple(kv for item in args[0].items() for kv in item) |
| 502 | |
| 503 | if len(args) % 2 != 0 or len(args) < 2: |
| 504 | raise ValueError( |
| 505 | "Provide an even amount of arguments as " |
| 506 | "option_context(pat, val, pat, val...)." |
| 507 | ) |
| 508 | |
| 509 | ops = tuple(zip(args[::2], args[1::2], strict=True)) |
| 510 | undo: tuple[tuple[Any, Any], ...] = () |
| 511 | try: |