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 github issue #6484 for benchmarks, and github issue #18330 for potential for improvement).

EXAMPLES:

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

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

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