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