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