Sections
Sub-Sections
Last Change
Annotate
Revision Log
Download
Plain Text
Original Format
Metanav
Preferences
About Trac
Links
Slowchop Studios
Gerald Kaszuba
Advertisement

root/betterprint/trunk/betterprint.py

Revision 24, 6.3 kB (checked in by gak, 3 years ago)

added gpl

  • Property svn:keywords set to Id Revision
Line 
1"""
2
3betterprint - A replacement module to pprint
4
5Copyright Gerald Kaszuba 2007
6
7This program is free software: you can redistribute it and/or modify
8it under the terms of the GNU General Public License as published by
9the Free Software Foundation, either version 3 of the License, or
10(at your option) any later version.
11
12This program is distributed in the hope that it will be useful,
13but WITHOUT ANY WARRANTY; without even the implied warranty of
14MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15GNU General Public License for more details.
16
17You should have received a copy of the GNU General Public License
18along with this program.  If not, see <http://www.gnu.org/licenses/>.
19
20"""
21
22import pprint as orig_pprint
23
24class MyPrettyPrinter(orig_pprint.PrettyPrinter):
25
26    def __init__(self, indent=4, width=80, depth=None, stream=None):
27        orig_pprint.PrettyPrinter.__init__(self, indent, width, depth, stream)
28        self._indent = indent
29        self._colours = {
30            'syntax': '\x1b[0;37m',
31            'key': '\x1b[0;93m',
32            'value': '\x1b[0;38m',
33        }
34
35    def pprint(self, object):
36        self._format(object, self._stream, self._indent, self._depth, {}, 0)
37        self._stream.write('\x1b[0m')
38        self._stream.write('\n')
39
40    def pformat(self, object):
41        sio = orig_pprint._StringIO()
42        self._format(object, sio, self._indent, self._depth, {}, 0)
43        return sio.getvalue()
44
45    def _format(self, object, stream, indent, allowance, context, level):
46        if not allowance:
47            allowance = 0
48        level = level + 1
49        objid = id(object)
50        if objid in context:
51            stream.write(self._colours['value'])
52            stream.write(orig_pprint._recursion(object))
53            self._recursive = True
54            self._readable = False
55            return
56        rep = self._repr(object, context, level - 1)
57        typ = type(object)
58        write = stream.write
59
60        r = getattr(typ, '__repr__', None)
61        if issubclass(typ, dict) and r is dict.__repr__:
62            write('{')
63            length = len(object)
64            if length:
65                write('\n')
66                write((indent * level) * ' ')
67                context[objid] = 1
68                items  = object.items()
69                items.sort()
70                key, ent = items[0]
71                rep = self._repr(key, context, level)
72                write(self._colours['key'])
73                write(rep)
74                write(self._colours['syntax'])
75                write(': ')
76                self._format(ent, stream, indent, allowance + 1, context, \
77                    level)
78                for key, ent in items[1:]:
79                    rep = self._repr(key, context, level)
80                    write(self._colours['syntax'])
81                    write(',')
82                    write('\n')
83                    write(' ' * (indent * level))
84                    write(self._colours['key'])
85                    write(rep)
86                    write(self._colours['syntax'])
87                    write(': ')
88                    self._format(ent, stream, indent, allowance + 1, \
89                        context, level)
90                del context[objid]
91                write(self._colours['syntax'])
92                write(',')
93                write('\n')
94                write(' ' * (indent * (level - 1)))
95            write(self._colours['syntax'])
96            write('}')
97            return
98
99        if (issubclass(typ, list) and r is list.__repr__) or \
100               (issubclass(typ, tuple) and r is tuple.__repr__):
101            write(self._colours['syntax'])
102            if issubclass(typ, list):
103                write('[')
104                endchar = self._colours['syntax'] + ']'
105            else:
106                write('(')
107                endchar = self._colours['syntax'] + ')'
108            length = len(object)
109            if length:
110                write('\n')
111                write(' ' * (indent * level))
112                context[objid] = 1
113                self._format(object[0], stream, indent, allowance + 1, \
114                    context, level)
115                for ent in object[1:]:
116                    write(self._colours['syntax'])
117                    write(',')
118                    write('\n')
119                    write(' ' * (indent * level))
120                    self._format(ent, stream, indent, allowance + 1, \
121                        context, level)
122                del context[objid]
123                write(self._colours['syntax'])
124                write(',')
125                write('\n')
126                write(' ' * (indent * (level - 1)))
127            write(endchar)
128            return
129
130        write(self._colours['value'])
131        write(rep)
132
133def __pprint(object, stream=None, indent=4, width=80, depth=None):
134    """Pretty-print a Python object to a stream [default is sys.stdout]."""
135    printer = MyPrettyPrinter(
136        stream=stream, indent=indent, width=width, depth=depth)
137    printer.pprint(object)
138
139def __pformat(object, indent=4, width=80, depth=None):
140    """Format a Python object into a pretty-printed representation."""
141    printer = MyPrettyPrinter(indent=indent, width=width, depth=depth)
142    return printer.pformat(object)
143
144orig_pprint.orig_pprint = __pprint
145orig_pprint.orig_pformat = __pformat
146
147pprint = __pprint
148pformat = __pformat
149isreadable = orig_pprint.isreadable
150isrecursive = orig_pprint.isrecursive
151saferepr = orig_pprint.saferepr
152PrettyPrinter = orig_pprint.PrettyPrinter
153
154if __name__ == '__main__':
155
156    pprint([1, 2, 3, 4])
157    pprint({
158        1: 'a',
159        2: 'b',
160        3: 'c',
161        4: 'd',
162    })
163    pprint({
164        1: {},
165        2: {},
166        3: {},
167        4: {},
168    })
169    pprint({
170        1: {1: {}},
171        2: {2: {}},
172        3: {3: {}},
173        4: {4: {}},
174    })
175    pprint({
176        1: [],
177        2: [],
178        3: [],
179        4: [],
180    })
181    pprint({
182        'a': [],
183        'b': [],
184        'c': [],
185        'd': [],
186    })
187    pprint({
188        1: [[]],
189        2: [[]],
190        3: [[]],
191        4: [[]],
192    })
193    pprint({
194        1: (),
195        2: (),
196        3: (),
197        4: (),
198    })
199
200    a = {}
201    a[0] = a
202    pprint(
203        [
204            [ 1, 2, 3 ],
205            a,
206            {
207                'dict': 'moo',
208                'wee': 123,
209                'ert': [1,2,3],
210            },
211            pprint,
212            'wow',
213            {'lots': {'of': {'depth': {'goes': 'here'}}}}
214        ],
215    )
Note: See TracBrowser for help on using the browser.