TheAlgorithms/Python · error · ValueError

n should be an integer greater than 0.

Error message

n should be an integer greater than 0.

What it means

Raised by LRUCache.__init__ when the capacity argument n is negative. Note the guard order: n == 0 (falsy) sets capacity to sys.maxsize (effectively unbounded), n < 0 raises, and any positive n sets the capacity. Also, _MAX_CAPACITY is a class attribute, so the last constructed instance overwrites the capacity for all instances.

Source

Thrown at other/least_recently_used.py:46

    >>> lru_cache
    LRUCache(4) => [5, 4, 'A', 3]

    """

    dq_store: deque[T]  # Cache store of keys
    key_reference: set[T]  # References of the keys in cache
    _MAX_CAPACITY: int = 10  # Maximum capacity of cache

    def __init__(self, n: int) -> None:
        """Creates an empty store and map for the keys.
        The LRUCache is set the size n.
        """
        self.dq_store = deque()
        self.key_reference = set()
        if not n:
            LRUCache._MAX_CAPACITY = sys.maxsize
        elif n < 0:
            raise ValueError("n should be an integer greater than 0.")
        else:
            LRUCache._MAX_CAPACITY = n

    def refer(self, x: T) -> None:
        """
        Looks for a page in the cache store and adds reference to the set.
        Remove the least recently used key if the store is full.
        Update store to reflect recent access.
        """
        if x not in self.key_reference:
            if len(self.dq_store) == LRUCache._MAX_CAPACITY:
                last_element = self.dq_store.pop()
                self.key_reference.remove(last_element)
        else:
            self.dq_store.remove(x)

        self.dq_store.appendleft(x)
        self.key_reference.add(x)

View on GitHub (pinned to f5988cc097)

Solutions

  1. Pass a positive integer capacity: LRUCache(10)
  2. Validate config-derived sizes: n = max(1, requested_size)
  3. Be aware LRUCache(0) means unbounded (sys.maxsize), not zero-capacity
  4. If you create several caches, avoid relying on per-instance capacity — _MAX_CAPACITY is class-wide in this implementation

Example fix

# before
cache = LRUCache(user_configured_size)  # -1 -> ValueError

# after
cache = LRUCache(max(1, user_configured_size))
Defensive patterns

Strategy: validation

Validate before calling

def valid_capacity(n) -> bool:
    return isinstance(n, int) and n >= 0  # note: 0 means unbounded here

Prevention

When it happens

Trigger: Calling LRUCache(-1) or LRUCache(-100). Separately, LRUCache(0) silently makes the cache unbounded, and constructing multiple caches with different n leaks the setting across instances because _MAX_CAPACITY is shared at class level.

Common situations: Computing capacity from configuration (e.g. size - 1 that can go negative) or from a subtraction that underflows; also multi-cache programs surprised by the shared class-level capacity.

Related errors


AI-assisted analysis of TheAlgorithms/Python@f5988cc097 (2026-08-14). Data as JSON: /api/errors/a9579d3c56cc52cc. Report an issue: GitHub.