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