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