Callable dictionaries¶
- class sage.misc.callable_dict.CallableDict[source]¶
- Bases: - dict- Callable dictionary. - This is a trivial subclass of - dictwith 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- CallableDictcan be used instead. Note however that, with the current implementation,- CallableDictis slightly slower than- d.__getitem__(see Issue #6484 for benchmarks, and 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 - >>> 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 - ValueErroris 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 - >>> 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