##// END OF EJS Templates
DOC: Add copyright comments.
Robert Kern -
Show More
@@ -1,162 +1,169
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 #-----------------------------------------------------------------------------
36 # Copyright (c) 2010, IPython Development Team.
37 #
38 # Distributed under the terms of the Modified BSD License.
39 #
40 # The full license is in the file COPYING.txt, distributed with this software.
41 #-----------------------------------------------------------------------------
35 42
36 43 # Stdlib imports
37 44 import abc
38 45 from cStringIO import StringIO
39 46
40 47 # Our own imports
41 48 from IPython.config.configurable import Configurable
42 49 from IPython.external import pretty
43 50 from IPython.utils.traitlets import Bool, Dict, Int, Str
44 51
45 52
46 53 #-----------------------------------------------------------------------------
47 54 # Classes and functions
48 55 #-----------------------------------------------------------------------------
49 56
50 57 class DefaultFormatter(Configurable):
51 58 """ The default pretty-printer.
52 59 """
53 60
54 61 # The ID of the formatter.
55 62 id = Str('default')
56 63
57 64 # The kind of data returned.
58 65 # This is often, but not always a MIME type.
59 66 format = Str('text/plain')
60 67
61 68 # Whether to pretty-print or not.
62 69 pprint = Bool(True, config=True)
63 70
64 71 # Whether to be verbose or not.
65 72 verbose = Bool(False, config=True)
66 73
67 74 # The maximum width.
68 75 max_width = Int(79, config=True)
69 76
70 77 # The newline character.
71 78 newline = Str('\n', config=True)
72 79
73 80 # The singleton prettyprinters.
74 81 # Maps the IDs of the builtin singleton objects to the format functions.
75 82 singleton_pprinters = Dict(config=True)
76 83 def _singleton_pprinters_default(self):
77 84 return pretty._singleton_pprinters.copy()
78 85
79 86 # The type-specific prettyprinters.
80 87 # Map type objects to the format functions.
81 88 type_pprinters = Dict(config=True)
82 89 def _type_pprinters_default(self):
83 90 return pretty._type_pprinters.copy()
84 91
85 92 # The deferred-import type-specific prettyprinters.
86 93 # Map (modulename, classname) pairs to the format functions.
87 94 deferred_pprinters = Dict(config=True)
88 95 def _deferred_pprinters_default(self):
89 96 return pretty._deferred_type_pprinters.copy()
90 97
91 98 #### FormatterABC interface ####
92 99
93 100 def __call__(self, obj):
94 101 """ Format the object.
95 102 """
96 103 if not self.pprint:
97 104 try:
98 105 return repr(obj)
99 106 except TypeError:
100 107 return ''
101 108 else:
102 109 stream = StringIO()
103 110 printer = pretty.RepresentationPrinter(stream, self.verbose,
104 111 self.max_width, self.newline,
105 112 singleton_pprinters=self.singleton_pprinters,
106 113 type_pprinters=self.type_pprinters,
107 114 deferred_pprinters=self.deferred_pprinters)
108 115 printer.pretty(obj)
109 116 printer.flush()
110 117 return stream.getvalue()
111 118
112 119
113 120 #### DefaultFormatter interface ####
114 121
115 122 def for_type(self, typ, func):
116 123 """
117 124 Add a pretty printer for a given type.
118 125 """
119 126 oldfunc = self.type_pprinters.get(typ, None)
120 127 if func is not None:
121 128 # To support easy restoration of old pprinters, we need to ignore
122 129 # Nones.
123 130 self.type_pprinters[typ] = func
124 131 return oldfunc
125 132
126 133 def for_type_by_name(self, type_module, type_name, func):
127 134 """
128 135 Add a pretty printer for a type specified by the module and name of
129 136 a type rather than the type object itself.
130 137 """
131 138 key = (type_module, type_name)
132 139 oldfunc = self.deferred_pprinters.get(key, None)
133 140 if func is not None:
134 141 # To support easy restoration of old pprinters, we need to ignore
135 142 # Nones.
136 143 self.deferred_pprinters[key] = func
137 144 return oldfunc
138 145
139 146
140 147 class FormatterABC(object):
141 148 """ Abstract base class for Formatters.
142 149 """
143 150 __metaclass__ = abc.ABCMeta
144 151
145 152 # The ID of the formatter.
146 153 id = 'abstract'
147 154
148 155 # The kind of data returned.
149 156 format = 'text/plain'
150 157
151 158 @abc.abstractmethod
152 159 def __call__(self, obj):
153 160 """ Return a JSONable representation of the object.
154 161
155 162 If the object cannot be formatted by this formatter, then return None
156 163 """
157 164 try:
158 165 return repr(obj)
159 166 except TypeError:
160 167 return None
161 168
162 169 FormatterABC.register(DefaultFormatter)
General Comments 0
You need to be logged in to leave comments. Login now