pola-rs/polars · error · ValueError

`maxsize` cannot be negative; found {n}

Error message

`maxsize` cannot be negative; found {n}

What it means

ValueError raised by the maxsize setter of the LRU cache: a negative integer {n} was assigned to cache.maxsize. The setter validates before trimming, so any negative bound on the cache capacity is rejected immediately.

Source

Thrown at py-polars/src/polars/_utils/cache.py:153

    def items(self) -> ItemsView[K, V]:
        """Return an iterable view of the cache's items (keys and values)."""
        return self._items.items()

    def keys(self) -> KeysView[K]:
        """Return an iterable view of the cache's keys."""
        return self._items.keys()

    @property
    def maxsize(self) -> int:
        return self._max_size

    @maxsize.setter
    def maxsize(self, n: int) -> None:
        """Set new maximum cache size; cache is trimmed if value is smaller."""
        if n < 0:
            msg = f"`maxsize` cannot be negative; found {n}"
            raise ValueError(msg)
        while len(self) > n:
            self.popitem()
        self._max_size = n

    def pop(self, key: K, default: D | NoDefault = NO_DEFAULT) -> V | D:
        """
        Remove specified key from the cache and return the associated value.

        If the key is not found, `default` is returned (if given).
        Otherwise, a KeyError is raised.
        """
        if (item := self._items.pop(key, default)) is NO_DEFAULT:
            msg = f"{key!r} not found in cache"
            raise KeyError(msg)
        return item

    def popitem(self) -> tuple[K, V]:
        """Remove the least recently used value; raises KeyError if cache is empty."""

View on GitHub (pinned to 9b5d73fd00)

Solutions

  1. Pass a non-negative maxsize (or None for unbounded).

Example fix

cache = LRUCache(maxsize=128)
Defensive patterns

Strategy: validation

When it happens

Trigger: Constructing a cache with maxsize < 0.

Common situations: See trigger scenarios.


AI-assisted analysis of pola-rs/polars@9b5d73fd00 (2026-08-19). Data as JSON: /api/errors/10a8abd592e57a3b. Report an issue: GitHub.