Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

# -*- coding: utf-8 -*- 

""" 

Callable dictionaries 

""" 

#***************************************************************************** 

# Copyright (C) 2015 Nicolas M. Thiéry <nthiery at users.sf.net> 

# 

# Distributed under the terms of the GNU General Public License (GPL) 

# as published by the Free Software Foundation; either version 2 of 

# the License, or (at your option) any later version. 

# http://www.gnu.org/licenses/ 

#***************************************************************************** 

  

cdef class CallableDict(dict): 

r""" 

Callable dictionary. 

  

This is a trivial subclass of :class:`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 

:class:`CallableDict` can be used instead. Note however that, with 

the current implementation, :class:`CallableDict` is slightly 

slower than ``d.__getitem__`` (see :trac:`6484` for benchmarks, and 

:trac:`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 :class:`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 

  

""" 

def __call__(self, key): 

r""" 

Return ``self[key]``. 

  

INPUT: 

  

- ``x`` -- any hashable object 

  

A :class:`ValueError` is raised if ``x`` is not in ``self``. 

  

TESTS:: 

  

sage: from sage.misc.callable_dict import CallableDict 

sage: from sage.combinat.words.morphism import CallableDict 

sage: d = CallableDict({'one': 1, 'zwei': 2, 'trois': 3}) 

sage: d('one'), d('zwei'), d('trois') 

(1, 2, 3) 

sage: d('x') 

Traceback (most recent call last): 

.... 

ValueError: 'x' is not in dict 

""" 

try: 

return self[key] 

except KeyError: 

raise ValueError(repr(key)+" is not in dict")