Repaso
Español
PythonIntermediatePY-36

You call a function decorated with @functools.lru_cache passing a list. What happens?

Options

  1. The list is converted to a tuple
  2. TypeError: unhashable type: 'list' (Correct option)
  3. The cache is skipped silently
  4. It works but never hits

Answer

TypeError: unhashable type: 'list'

Why

lru_cache remembers results in a dictionary, using the arguments as the key.

Dictionary keys must be hashable (unchangeable). A list can change, so it is not hashable and you get a TypeError.

Pass a tuple instead of a list.

Remember

Arguments of a cached function must be hashable.

Key terms

Practice this question in Repaso