pandas-dev/pandas · error · ValueError

Provide an even amount of arguments as option_context(pat, v

Error message

Provide an even amount of arguments as option_context(pat, val, pat, val...).

What it means

Raised by option_context (config.py:506-510) as a ValueError when the number of positional args is odd or fewer than 2. Like set_option it accepts (pattern, value) pairs or a single dict, which is unwrapped before the check.

Source

Thrown at pandas/_config/config.py:507

    Notes
    -----
    For all available options, please view the :ref:`User Guide <options.available>`
    or use ``pandas.describe_option()``.

    Examples
    --------
    >>> from pandas import option_context
    >>> with option_context("display.max_rows", 10, "display.max_columns", 5):
    ...     pass
    >>> with option_context({"display.max_rows": 10, "display.max_columns": 5}):
    ...     pass
    """
    if len(args) == 1 and isinstance(args[0], dict):
        args = tuple(kv for item in args[0].items() for kv in item)

    if len(args) % 2 != 0 or len(args) < 2:
        raise ValueError(
            "Provide an even amount of arguments as "
            "option_context(pat, val, pat, val...)."
        )

    ops = tuple(zip(args[::2], args[1::2], strict=True))
    undo: tuple[tuple[Any, Any], ...] = ()
    try:
        undo = tuple((pat, get_option(pat)) for pat, val in ops)
        for pat, val in ops:
            set_option(pat, val)
        yield
    finally:
        for pat, val in undo:
            set_option(pat, val)


def register_option(
    key: str,

View on GitHub (pinned to 71959b8cb9)

Solutions

  1. Pass pairs: with pd.option_context('display.max_columns', 10, 'display.max_rows', 20): ....
  2. Pass a dict: with pd.option_context({'display.max_columns': 10}): ....
  3. Validate len(args) is even and >= 2 before constructing the call.

Example fix

# before
with pd.option_context('display.max_columns'):  # ValueError
    ...

# after
with pd.option_context('display.max_columns', 10):
    ...
Defensive patterns

Strategy: validation

Validate before calling

def safe_option_context(*args):
    assert len(args) >= 2 and len(args) % 2 == 0, 'option_context needs (pat, val) pairs'
    return pd.option_context(*args)

Prevention

When it happens

Trigger: with pd.option_context('display.max_columns'): ... (1 arg), or an odd-length tuple of pairs.

Common situations: Forgetting the value, or passing an odd number of args after refactoring a context block.

Related errors


AI-assisted analysis of pandas-dev/pandas@71959b8cb9 (2026-08-07). Data as JSON: /api/errors/ea914f480a3d689b. Report an issue: GitHub.