##// END OF EJS Templates
ENH: Documentation for configuring the DefaultFormatter.
Robert Kern -
Show More
@@ -1,123 +1,152 b''
1 1 # -*- coding: utf-8 -*-
2 2 """Displayhook formatters.
3 3
4 The DefaultFormatter is always present and may be configured from the ipython_config.py file. For example, to add a pretty-printer for a numpy.dtype object::
5
6 def dtype_pprinter(obj, p, cycle):
7 if cycle:
8 return p.text('dtype(...)')
9 if hasattr(obj, 'fields'):
10 if obj.fields is None:
11 p.text(repr(obj))
12 else:
13 p.begin_group(7, 'dtype([')
14 for i, field in enumerate(obj.descr):
15 if i > 0:
16 p.text(',')
17 p.breakable()
18 p.pretty(field)
19 p.end_group(7, '])')
20
21 c.DefaultFormatter.deferred_pprinters = {
22 ('numpy', 'dtype'): dtype_pprinter,
23 }
24
25 The deferred_pprinters dictionary is the preferred way to configure these
26 pretty-printers. This allows you to define the pretty-printer without needing to
27 import the type itself. The dictionary maps (modulename, typename) pairs to
28 a function.
29
30 See the `IPython.external.pretty` documentation for how to write
31 pretty-printer functions.
32
4 33 Authors:
5 34
6 35 * Robert Kern
7 36 """
8 37
9 38 import abc
10 39 from cStringIO import StringIO
11 40
12 41 from IPython.config.configurable import Configurable
13 42 from IPython.external import pretty
14 43 from IPython.utils.traitlets import Bool, Dict, Int, Str
15 44
16 45
17 46 class DefaultFormatter(Configurable):
18 47 """ The default pretty-printer.
19 48 """
20 49
21 50 # The ID of the formatter.
22 51 id = Str('default')
23 52
24 53 # The kind of data returned.
25 54 format = Str('text')
26 55
27 56 # Whether to pretty-print or not.
28 57 pprint = Bool(True, config=True)
29 58
30 59 # Whether to be verbose or not.
31 60 verbose = Bool(False, config=True)
32 61
33 62 # The maximum width.
34 63 max_width = Int(79, config=True)
35 64
36 65 # The newline character.
37 66 newline = Str('\n', config=True)
38 67
39 68 # The singleton prettyprinters.
40 69 # Maps the IDs of the builtin singleton objects to the format functions.
41 70 singleton_pprinters = Dict(config=True)
42 71 def _singleton_pprinters_default(self):
43 72 return pretty._singleton_pprinters.copy()
44 73
45 74 # The type-specific prettyprinters.
46 75 # Map type objects to the format functions.
47 76 type_pprinters = Dict(config=True)
48 77 def _type_pprinters_default(self):
49 78 return pretty._type_pprinters.copy()
50 79
51 80 # The deferred-import type-specific prettyprinters.
52 81 # Map (modulename, classname) pairs to the format functions.
53 82 deferred_pprinters = Dict(config=True)
54 83 def _deferred_pprinters_default(self):
55 84 return pretty._deferred_type_pprinters.copy()
56 85
57 86 #### FormatterABC interface ####
58 87
59 88 def __call__(self, obj):
60 89 """ Format the object.
61 90 """
62 91 if not self.pprint:
63 92 try:
64 93 return repr(obj)
65 94 except TypeError:
66 95 return ''
67 96 else:
68 97 stream = StringIO()
69 98 printer = pretty.RepresentationPrinter(stream, self.verbose,
70 99 self.max_width, self.newline,
71 100 singleton_pprinters=self.singleton_pprinters,
72 101 type_pprinters=self.type_pprinters,
73 102 deferred_pprinters=self.deferred_pprinters)
74 103 printer.pretty(obj)
75 104 printer.flush()
76 105 return stream.getvalue()
77 106
78 107
79 108 #### DefaultFormatter interface ####
80 109
81 110 def for_type(self, typ, func):
82 111 """
83 112 Add a pretty printer for a given type.
84 113 """
85 114 oldfunc = self.type_pprinters.get(typ, None)
86 115 if func is not None:
87 116 # To support easy restoration of old pprinters, we need to ignore
88 117 # Nones.
89 118 self.type_pprinters[typ] = func
90 119 return oldfunc
91 120
92 121 def for_type_by_name(self, type_module, type_name, func):
93 122 """
94 123 Add a pretty printer for a type specified by the module and name of
95 124 a type rather than the type object itself.
96 125 """
97 126 key = (type_module, type_name)
98 127 oldfunc = self.deferred_pprinters.get(key, None)
99 128 if func is not None:
100 129 # To support easy restoration of old pprinters, we need to ignore
101 130 # Nones.
102 131 self.deferred_pprinters[key] = func
103 132 return oldfunc
104 133
105 134
106 135 class FormatterABC(object):
107 136 """ Abstract base class for Formatters.
108 137 """
109 138 __metaclass__ = abc.ABCMeta
110 139
111 140 # The ID of the formatter.
112 141 id = 'abstract'
113 142
114 143 # The kind of data returned.
115 144 format = 'text'
116 145
117 146 @abc.abstractmethod
118 147 def __call__(self, obj):
119 148 """ Return a JSONable representation of the object.
120 149 """
121 150 return repr(obj)
122 151
123 152 FormatterABC.register(DefaultFormatter)
General Comments 0
You need to be logged in to leave comments. Login now