pola-rs/polars · error · ValueError
`maxsize` cannot be negative; found
Error message
`maxsize` cannot be negative; found {n} What it means
The Cache.maxsize setter validates that the new maximum size is non-negative; a negative value raises ValueError immediately. The setter also trims the cache down to the new limit while len(cache) exceeds it.
Solutions
- Pass a non-negative integer: `cache.maxsize = max(0, configured_size)`
- Validate the configured value before assignment (clamp to >= 0 or reject)
- Trace the source of the negative number (config parsing/subtraction bug) and fix it at the origin
- Use 0 to disable caching rather than a negative sentinel
Example fix
// before
cache.maxsize = config["cache_size"] # ValueError if -1
// after
size = config.get("cache_size", 128)
cache.maxsize = max(0, int(size)) Defensive patterns
Strategy: validation
Validate before calling
n = int(config.get('cache_size', 128))
if n < 0:
raise ValueError('cache_size must be >= 0')
cache.maxsize = n Type guard
def valid_maxsize(n) -> bool:
return isinstance(n, int) and not isinstance(n, bool) and n >= 0 Try / catch
try:
cache.maxsize = configured
except ValueError:
cache.maxsize = 128 # safe default Prevention
- Clamp config-derived sizes with max(0, value) before assignment
- Validate numeric config fields at startup, not at use site
- Avoid negative sentinels to mean 'disabled'; use 0 or None semantics explicitly
- Add unit tests for boundary config values (0, -1)
When it happens
Trigger: Assigning a negative number to the cache's maxsize property, e.g. `cache.maxsize = -1`, typically from an unvalidated config value or arithmetic that underflowed.
Common situations: Config files/env vars parsed without validation (e.g. "maxsize": -1); computing size from a negative budget; wiring UI input straight into maxsize.
Understand the failure class
Background: "value must be between 0 and 1" / "out of range" / "must not be negative" errors: fixing range-validation failures across open-source libraries — this error's family across 42 libraries.
Related errors
- =" " should be a single byte character or empty, but is…
- =" " should be a single byte character, but is bytes long
- cannot use credential_provider when passing a DeltaTable…
- `format` must be one of
- `how` must be one of
AI-assisted analysis of pola-rs/polars@fe841f959e (2026-09-18).
Data as JSON: /api/errors/10a8abd592e57a3b.
Report an issue: GitHub.
Appendix: 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 fe841f959e)