Callable dictionaries - Utilities

Skip to content
Back to top
View this page
Edit this page

# Callable dictionaries

class sage.misc.callable_dict.CallableDict

  Bases: `dict`

  Callable dictionary.

  This is a trivial subclass of `dict` with an alternative view as a function.

  Typical use cases involve passing a dictionary \(d\) down to some tool that takes a function as input. The usual idiom in such use cases is to pass the `d.__getitem__` bound method. A pitfall is that this object is not picklable. When this feature is desired, a `CallableDict` can be used instead. Note however that, with the current implementation, `CallableDict` is slightly slower than `d.__getitem__` (see Issue #6484 for benchmarks, and Issue #18330 for potential for improvement).

  EXAMPLES:

  Sage

      sage: from sage.misc.callable_dict import CallableDict
      sage: d = CallableDict({'one': 1, 'zwei': 2, 'trois': 3})
      sage: d['zwei']
      2
      sage: d('zwei')
      2

  Python

      >>> from sage.all import *
      >>> from sage.misc.callable_dict import CallableDict
      >>> d = CallableDict({'one': Integer(1), 'zwei': Integer(2), 'trois': Integer(3)})
      >>> d['zwei']
      2
      >>> d('zwei')
      2

  In case the input is not in the dictionary, a `ValueError` is raised, for consistency with the function call syntax:

  Sage

      sage: d[1]
      Traceback (most recent call last):
      ...
      KeyError: 1
      sage: d(1)
      Traceback (most recent call last):
      ...
      ValueError: 1 is not in dict

  [Python]

      >>> from sage.all import *
      >>> d[Integer(1)]
      Traceback (most recent call last):
      ...
      KeyError: 1
      >>> d(Integer(1))
      Traceback (most recent call last):
      ...
      ValueError: 1 is not in dict