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