jk_prettyprintobj 0.2021.1.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,3 @@
1
+ include README.md
2
+ include LICENSE.txt
3
+
@@ -0,0 +1,54 @@
1
+ Metadata-Version: 2.1
2
+ Name: jk_prettyprintobj
3
+ Version: 0.2021.1.4
4
+ Summary: This python module provides a mixin for creating pretty debugging output for objects. This is especially useful for semi-complex data structures.
5
+ Home-page: UNKNOWN
6
+ Author: Jürgen Knauth
7
+ Author-email: pubsrc@binary-overflow.de
8
+ License: Apache2
9
+ Description: jk_prettyprintobj
10
+ ========
11
+
12
+ Introduction
13
+ ------------
14
+
15
+ This python module provides a mixin for dumping objects.
16
+
17
+ Information about this module can be found here:
18
+
19
+ * [github.org](https://github.com/jkpubsrc/python-module-jk-prettyprintobj)
20
+ * [pypi.python.org](https://pypi.python.org/pypi/jk_prettyprintobj)
21
+
22
+ How to use this module
23
+ ----------------------
24
+
25
+ ### ....
26
+
27
+ ....
28
+
29
+ Contact Information
30
+ -------------------
31
+
32
+ This is Open Source code. That not only gives you the possibility of freely using this code it also
33
+ allows you to contribute. Feel free to contact the author(s) of this software listed below, either
34
+ for comments, collaboration requests, suggestions for improvement or reporting bugs:
35
+
36
+ * Jürgen Knauth: pubsrc@binary-overflow.de
37
+
38
+ License
39
+ -------
40
+
41
+ This software is provided under the following license:
42
+
43
+ * Apache Software License 2.0
44
+
45
+
46
+
47
+
48
+ Keywords: pretty-print,debugging,debug
49
+ Platform: UNKNOWN
50
+ Classifier: Development Status :: 5 - Production/Stable
51
+ Classifier: License :: OSI Approved :: Apache Software License
52
+ Classifier: Programming Language :: Python :: 3
53
+ Classifier: Topic :: Software Development :: Testing
54
+ Description-Content-Type: text/markdown
@@ -0,0 +1,38 @@
1
+ jk_prettyprintobj
2
+ ========
3
+
4
+ Introduction
5
+ ------------
6
+
7
+ This python module provides a mixin for dumping objects.
8
+
9
+ Information about this module can be found here:
10
+
11
+ * [github.org](https://github.com/jkpubsrc/python-module-jk-prettyprintobj)
12
+ * [pypi.python.org](https://pypi.python.org/pypi/jk_prettyprintobj)
13
+
14
+ How to use this module
15
+ ----------------------
16
+
17
+ ### ....
18
+
19
+ ....
20
+
21
+ Contact Information
22
+ -------------------
23
+
24
+ This is Open Source code. That not only gives you the possibility of freely using this code it also
25
+ allows you to contribute. Feel free to contact the author(s) of this software listed below, either
26
+ for comments, collaboration requests, suggestions for improvement or reporting bugs:
27
+
28
+ * Jürgen Knauth: pubsrc@binary-overflow.de
29
+
30
+ License
31
+ -------
32
+
33
+ This software is provided under the following license:
34
+
35
+ * Apache Software License 2.0
36
+
37
+
38
+
@@ -0,0 +1,52 @@
1
+
2
+
3
+
4
+ #
5
+ # This class wraps around an integer value and represents a value in binary representation.
6
+ # This is purely used to simlify output.
7
+ #
8
+ class _Bits(object):
9
+
10
+ __slots__ = (
11
+ "value",
12
+ )
13
+
14
+ def __init__(self, value:int):
15
+ assert isinstance(value, int)
16
+ assert value >= 0
17
+ self.value = value
18
+ #
19
+
20
+ def __repr__(self):
21
+ s = bin(self.value)[2:]
22
+ n = len(s)
23
+ if (n == 8) or (n == 16) or (n == 32) or (n == 64):
24
+ return "b" + s
25
+ elif n < 8:
26
+ r = n % 8
27
+ return "b" + ("0" * (8 - r)) + s
28
+ elif n < 16:
29
+ r = n % 16
30
+ return "b" + ("0" * (16 - r)) + s
31
+ elif n < 32:
32
+ r = n % 32
33
+ return "b" + ("0" * (32 - r)) + s
34
+ elif n < 64:
35
+ r = n % 64
36
+ return "b" + ("0" * (64 - r)) + s
37
+ else:
38
+ r = n % 8
39
+ return "b" + ("0" * (8 - r)) + s
40
+ #
41
+
42
+ def __str__(self):
43
+ return self.__repr__()
44
+ #
45
+
46
+ #
47
+
48
+
49
+
50
+
51
+
52
+
@@ -0,0 +1,42 @@
1
+
2
+
3
+
4
+ #
5
+ # This class wraps around an integer value and represents a hex value.
6
+ # This is purely used to simlify output.
7
+ #
8
+ class _Hex(object):
9
+
10
+ __slots__ = (
11
+ "value",
12
+ )
13
+
14
+ def __init__(self, value:int):
15
+ assert isinstance(value, int)
16
+ assert value >= 0
17
+ self.value = value
18
+ #
19
+
20
+ def __repr__(self):
21
+ s = hex(self.value)[2:]
22
+ n = len(s)
23
+ if n == 1:
24
+ return "x0" + s
25
+ elif n == 2:
26
+ return "x" + s
27
+ else:
28
+ r = n % 4
29
+ return "x" + ("0" * (4 - r)) + s
30
+ #
31
+
32
+ def __str__(self):
33
+ return self.__repr__()
34
+ #
35
+
36
+ #
37
+
38
+
39
+
40
+
41
+
42
+
@@ -0,0 +1,17 @@
1
+ 
2
+
3
+ __version__ = "0.2021.1.4"
4
+
5
+
6
+
7
+ from .dumper import DumpMixin, Dumper, DumpCtx
8
+
9
+
10
+
11
+
12
+
13
+
14
+
15
+
16
+
17
+
@@ -0,0 +1,532 @@
1
+
2
+
3
+ import typing
4
+ import collections
5
+ #import datetime
6
+
7
+ from ._Hex import _Hex
8
+ from ._Bits import _Bits
9
+
10
+
11
+
12
+
13
+
14
+
15
+ class DumperSettings(object):
16
+
17
+ def __init__(self):
18
+ self.showPrimitivesWithType = False
19
+ self.showDictKeysWithType = False
20
+ self.showComplexStructsWithType = False
21
+ self.compactSequencLimit = 8
22
+ #
23
+
24
+ #
25
+
26
+ DEFAULT_DUMPER_SETTINGS = DumperSettings()
27
+
28
+
29
+
30
+
31
+ def _str_shortenText(text:str) -> str:
32
+ if len(text) > 40:
33
+ return text[:40] + "..."
34
+ else:
35
+ return text
36
+ #
37
+
38
+ def _float_roundTo7FractionDigits(data:typing.Union[int,float]) -> float:
39
+ return round(data, 7)
40
+ #
41
+
42
+ def _float_roundTo6FractionDigits(data:typing.Union[int,float]) -> float:
43
+ return round(data, 6)
44
+ #
45
+
46
+ def _float_roundTo5FractionDigits(data:typing.Union[int,float]) -> float:
47
+ return round(data, 5)
48
+ #
49
+
50
+ def _float_roundTo4FractionDigits(data:typing.Union[int,float]) -> float:
51
+ return round(data, 4)
52
+ #
53
+
54
+ def _float_roundTo3FractionDigits(data:typing.Union[int,float]) -> float:
55
+ return round(data, 3)
56
+ #
57
+
58
+ def _float_roundTo2FractionDigits(data:typing.Union[int,float]) -> float:
59
+ return round(data, 2)
60
+ #
61
+
62
+ def _float_roundTo1FractionDigits(data:typing.Union[int,float]) -> float:
63
+ return round(data, 1)
64
+ #
65
+
66
+ def _int_toHex(data:int) -> typing.Union[int,str]:
67
+ if data < 0:
68
+ return data
69
+ return _Hex(data)
70
+ #
71
+
72
+ def _int_toBits(data:int) -> typing.Union[int,str]:
73
+ if data < 0:
74
+ return data
75
+ return _Bits(data)
76
+ #
77
+
78
+
79
+
80
+
81
+ POST_PROCESSORS = {
82
+ "shorten": (str, _str_shortenText),
83
+ "hex": (int, _int_toHex),
84
+ "bit": (int, _int_toBits),
85
+ "round1": ((float, int), _float_roundTo1FractionDigits),
86
+ "round2": ((float, int), _float_roundTo2FractionDigits),
87
+ "round3": ((float, int), _float_roundTo3FractionDigits),
88
+ "round4": ((float, int), _float_roundTo4FractionDigits),
89
+ "round5": ((float, int), _float_roundTo5FractionDigits),
90
+ "round6": ((float, int), _float_roundTo6FractionDigits),
91
+ "round7": ((float, int), _float_roundTo7FractionDigits),
92
+
93
+ "str_shorten": (str, _str_shortenText),
94
+ "float_round7": ((float, int), _float_roundTo7FractionDigits),
95
+ "float_round6": ((float, int), _float_roundTo6FractionDigits),
96
+ "float_round5": ((float, int), _float_roundTo5FractionDigits),
97
+ "float_round4": ((float, int), _float_roundTo4FractionDigits),
98
+ "float_round3": ((float, int), _float_roundTo3FractionDigits),
99
+ "float_round2": ((float, int), _float_roundTo2FractionDigits),
100
+ "float_round1": ((float, int), _float_roundTo1FractionDigits),
101
+ "int_hex": (int, _int_toHex),
102
+ "int_bit": (int, _int_toBits),
103
+ }
104
+
105
+
106
+
107
+
108
+ class _Omitted:
109
+ pass
110
+ #
111
+
112
+ _OMITTED = _Omitted()
113
+
114
+
115
+
116
+
117
+
118
+ class DumpCtx(object):
119
+
120
+ _TYPE_MAP = {}
121
+
122
+ def __init__(self, s:DumperSettings, outputLines:list, exitAppend:str, prefix:str):
123
+ self.__s = s
124
+ self.outputLines = outputLines
125
+ self.__exitAppend = exitAppend
126
+ self.prefix = prefix
127
+ #
128
+
129
+ ################################################################################################################################
130
+ #### Methods that should be called by implementors
131
+ ################################################################################################################################
132
+
133
+ #
134
+ # if you implement `void _dump(DumpCtx ctx)` invoke this method to dump a specific variable explicitely.
135
+ #
136
+ def dumpVar(self, varName:str, value, processorName:str = None) -> None:
137
+ self._dumpX(varName + " = ", value, processorName)
138
+ #
139
+
140
+ #
141
+ # ????
142
+ #
143
+ def dumpVars(self, caller, *args):
144
+ if len(args) == 0:
145
+ if hasattr(caller, "_dumpVarNames"):
146
+ varNames = caller._dumpVarNames()
147
+ assert isinstance(varNames, (list, tuple))
148
+ else:
149
+ raise Exception("Specify either variable names or a list of variables to dump!")
150
+
151
+ elif len(args) == 1:
152
+ if isinstance(args[0], str):
153
+ varNames = args
154
+ elif isinstance(args[0], (tuple, list)):
155
+ varNames = args[0]
156
+ else:
157
+ raise Exception("Unexpected data in args: " + repr(args))
158
+
159
+ else:
160
+ varNames = args
161
+
162
+ for varName in varNames:
163
+ assert isinstance(varName, str)
164
+
165
+ processorName = None
166
+ pos = varName.find(":")
167
+ if pos == 0:
168
+ raise Exception()
169
+ elif pos > 0:
170
+ processorName = varName[pos+1:]
171
+ varName = varName[:pos]
172
+
173
+ value = getattr(caller, varName)
174
+ self._dumpX(varName + " = ", value, processorName)
175
+ #
176
+
177
+ ################################################################################################################################
178
+ #### Dispatcher method
179
+ ################################################################################################################################
180
+
181
+ #
182
+ # This method outputs a value (recursively).
183
+ # To achieve this this method analyses the data type of the specified value and invokes individual type processing methods if available.
184
+ #
185
+ def _dumpX(self, extraPrefix:str, value, processorName:str = None):
186
+ if value is None:
187
+ self._dumpPrimitive(extraPrefix, value, processorName)
188
+ return
189
+
190
+ t = type(value)
191
+ m = DumpCtx._TYPE_MAP.get(t)
192
+ if m:
193
+ m(self, extraPrefix, value, processorName)
194
+ return
195
+
196
+ if isinstance(value, DumpMixin):
197
+ self._dumpObj(extraPrefix, value)
198
+ return
199
+
200
+ self.outputLines.append(self.prefix + extraPrefix + repr(value))
201
+ #
202
+
203
+ ################################################################################################################################
204
+ #### Type specific dump methods
205
+ ################################################################################################################################
206
+
207
+ def _isDumpableObj(self, obj):
208
+ if hasattr(obj, "_dump"):
209
+ return True
210
+ if hasattr(obj, "_dumpVarNames"):
211
+ return True
212
+ return False
213
+ #
214
+
215
+ #
216
+ # Dump the specified object.
217
+ #
218
+ def _dumpObj(self, extraPrefix:str, value:object, processorName:str = None):
219
+ self.outputLines.append(self.prefix + extraPrefix + "<" + value.__class__.__name__ + "(")
220
+
221
+ ctx = DumpCtx(self.__s, self.outputLines, None, self.prefix + "\t")
222
+ with ctx as ctx2:
223
+ if hasattr(value, "_dump"):
224
+ value._dump(ctx2)
225
+ elif hasattr(value, "_dumpVarNames"):
226
+ ctx2.dumpVars(value)
227
+ else:
228
+ raise Exception("Improper object encountered for prettyprinting: " + type(value).__name__)
229
+
230
+ self.outputLines.append(self.prefix + ")>")
231
+ #
232
+
233
+ #
234
+ # Dump the specified dictionary.
235
+ #
236
+ def _dumpDict(self, extraPrefix:str, value:dict, processorName:str = None):
237
+ e = "dict:" if self.__s.showComplexStructsWithType else ""
238
+
239
+ self.outputLines.append(self.prefix + extraPrefix + e + "{")
240
+
241
+ ctx = DumpCtx(self.__s, self.outputLines, None, self.prefix + "\t")
242
+ with ctx as ctx2:
243
+ for k, v in value.items():
244
+ if processorName == "omitValues":
245
+ v = _OMITTED
246
+ ctx2._dumpX(self._dictKeyToStr(k) + " : ", v)
247
+ self.outputLines[-1] += ","
248
+
249
+ self.outputLines.append(self.prefix + "}")
250
+ #
251
+
252
+ def _dumpOrderedDict(self, extraPrefix:str, value:dict, processorName:str = None):
253
+ e = "OrderedDict:" if self.__s.showComplexStructsWithType else ""
254
+
255
+ self.outputLines.append(self.prefix + extraPrefix + e + "{")
256
+
257
+ ctx = DumpCtx(self.__s, self.outputLines, None, self.prefix + "\t")
258
+ with ctx as ctx2:
259
+ for k, v in value.items():
260
+ ctx2._dumpX(self._dictKeyToStr(k) + " : ", v)
261
+ self.outputLines[-1] += ","
262
+
263
+ self.outputLines.append(self.prefix + "}")
264
+ #
265
+
266
+ #
267
+ # Dump the specified list.
268
+ #
269
+ def _dumpList(self, extraPrefix:str, value:list, processorName:str = None):
270
+ e = "list:" if self.__s.showComplexStructsWithType else ""
271
+
272
+ if self._canCompactSequence(value):
273
+ self.outputLines.append(self.prefix + extraPrefix + e + "[ " + self._compactSequence(value, processorName) + " ]")
274
+
275
+ else:
276
+ self.outputLines.append(self.prefix + extraPrefix + e + "[")
277
+
278
+ ctx = DumpCtx(self.__s, self.outputLines, None, self.prefix + "\t")
279
+ with ctx as ctx2:
280
+ for vItem in value:
281
+ ctx2._dumpX("", vItem, processorName)
282
+ self.outputLines[-1] += ","
283
+
284
+ self.outputLines.append(self.prefix + "]")
285
+ #
286
+
287
+ #
288
+ # Dump the specified tuple.
289
+ #
290
+ def _dumpTuple(self, extraPrefix:str, value:set, processorName:str = None):
291
+ e = "tuple:" if self.__s.showComplexStructsWithType else ""
292
+
293
+ if self._canCompactSequence(value):
294
+ self.outputLines.append(self.prefix + extraPrefix + e + "( " + self._compactSequence(value, processorName) + " )")
295
+
296
+ else:
297
+ self.outputLines.append(self.prefix + extraPrefix + e + "(")
298
+
299
+ ctx = DumpCtx(self.__s, self.outputLines, None, self.prefix + "\t")
300
+ with ctx as ctx2:
301
+ for vItem in value:
302
+ ctx2._dumpX("", vItem, processorName)
303
+ self.outputLines[-1] += ","
304
+
305
+ self.outputLines.append(self.prefix + ")")
306
+ #
307
+
308
+ #
309
+ # Dump the specified set.
310
+ #
311
+ def _dumpSet(self, extraPrefix:str, value:set, processorName:str = None):
312
+ e = "set:" if self.__s.showComplexStructsWithType else ""
313
+
314
+ sequence = sorted(value)
315
+
316
+ if self._canCompactSequence(sequence):
317
+ self.outputLines.append(self.prefix + extraPrefix + e + "{ " + self._compactSequence(sequence, processorName) + " }")
318
+
319
+ else:
320
+ self.outputLines.append(self.prefix + extraPrefix + e + "{")
321
+
322
+ ctx = DumpCtx(self.__s, self.outputLines, None, self.prefix + "\t")
323
+ with ctx as ctx2:
324
+ for vItem in sequence:
325
+ ctx2._dumpX("", vItem, processorName)
326
+ self.outputLines[-1] += ","
327
+
328
+ self.outputLines.append(self.prefix + "}")
329
+ #
330
+
331
+ #
332
+ # Dump the specified frozen set.
333
+ #
334
+ def _dumpFrozenSet(self, extraPrefix:str, value:frozenset, processorName:str = None):
335
+ e = "frozenset:" if self.__s.showComplexStructsWithType else "frozenset"
336
+
337
+ sequence = sorted(value)
338
+
339
+ if self._canCompactSequence(sequence):
340
+ self.outputLines.append(self.prefix + extraPrefix + e + "{ " + self._compactSequence(sequence, processorName) + " }")
341
+
342
+ else:
343
+ self.outputLines.append(self.prefix + extraPrefix + e + "{")
344
+
345
+ ctx = DumpCtx(self.__s, self.outputLines, None, self.prefix + "\t")
346
+ with ctx as ctx2:
347
+ for vItem in sequence:
348
+ ctx2._dumpX("", vItem, processorName)
349
+ self.outputLines[-1] += ","
350
+
351
+ self.outputLines.append(self.prefix + "}")
352
+ #
353
+
354
+ def _dumpPrimitive(self, extraPrefix:str, value, processorName:str = None):
355
+ self.outputLines.append(self.prefix + extraPrefix + self._primitiveValueToStr(value, processorName))
356
+ #
357
+
358
+ def _dumpOmitted(self, extraPrefix:str, value, processorName:str = None):
359
+ self.outputLines.append(self.prefix + extraPrefix + "...")
360
+ #
361
+
362
+ ################################################################################################################################
363
+ #### Helper methods
364
+ ################################################################################################################################
365
+
366
+ def _canCompactSequence(self, someSequence):
367
+ if len(someSequence) > self.__s.compactSequencLimit:
368
+ return False
369
+ for v in someSequence:
370
+ if (v is not None) and (type(v) not in [ int, str, float, bool ]):
371
+ return False
372
+ return True
373
+ #
374
+
375
+ def _compactSequence(self, someSequence, processorName:str = None) -> str:
376
+ ret = []
377
+ for v in someSequence:
378
+ ret.append(self._primitiveValueToStr(v, processorName))
379
+ return ", ".join(ret)
380
+ #
381
+
382
+ #
383
+ # Converts a single dictionary key to str
384
+ #
385
+ def _dictKeyToStr(self, value):
386
+ if value is None:
387
+ return "(null)"
388
+ else:
389
+ if self.__s.showDictKeysWithType:
390
+ if isinstance(value, float):
391
+ return "float:" + repr(value)
392
+ elif isinstance(value, bool):
393
+ return "bool:" + repr(value)
394
+ elif isinstance(value, int):
395
+ return "int:" + repr(value)
396
+ else:
397
+ return type(value).__name__ + ":" + repr(value)
398
+ else:
399
+ return repr(value)
400
+ #
401
+
402
+ #
403
+ # Converts a single primitive value to str
404
+ #
405
+ def _primitiveValueToStr(self, value, processorName:str = None):
406
+ if value is None:
407
+ return "(null)"
408
+ else:
409
+ # process value before converting it to str
410
+ if processorName:
411
+ if processorName not in POST_PROCESSORS:
412
+ raise Exception("No such postprocessor: " + repr(processorName))
413
+ postProcessorTypeCompatibility, postProcessor = POST_PROCESSORS[processorName]
414
+ if isinstance(value, postProcessorTypeCompatibility):
415
+ value = postProcessor(value)
416
+
417
+ # return value as str
418
+ if self.__s.showPrimitivesWithType:
419
+ if isinstance(value, float):
420
+ return "float:" + repr(value)
421
+ elif isinstance(value, bool):
422
+ return "bool:" + repr(value)
423
+ elif isinstance(value, int):
424
+ return "int:" + repr(value)
425
+ elif isinstance(value, str):
426
+ return "str:" + repr(value)
427
+ else:
428
+ return type(value).__name__ + ":" + repr(value)
429
+ else:
430
+ if isinstance(value, str):
431
+ return repr(value)
432
+ else:
433
+ return repr(value)
434
+ #
435
+
436
+ ################################################################################################################################
437
+ #### Magic methods
438
+ ################################################################################################################################
439
+
440
+ def __enter__(self):
441
+ return self
442
+ #
443
+
444
+ def __exit__(self, *args):
445
+ if self.__exitAppend:
446
+ self.outputLines.append(self.__exitAppend)
447
+ return False
448
+ #
449
+
450
+ #
451
+
452
+
453
+
454
+
455
+ #
456
+ # Now let's register the types
457
+ #
458
+ if not DumpCtx._TYPE_MAP:
459
+ DumpCtx._TYPE_MAP[set] = DumpCtx._dumpSet
460
+ DumpCtx._TYPE_MAP[frozenset] = DumpCtx._dumpFrozenSet
461
+ DumpCtx._TYPE_MAP[tuple] = DumpCtx._dumpTuple
462
+ DumpCtx._TYPE_MAP[list] = DumpCtx._dumpList
463
+ DumpCtx._TYPE_MAP[collections.OrderedDict] = DumpCtx._dumpOrderedDict
464
+ DumpCtx._TYPE_MAP[dict] = DumpCtx._dumpDict
465
+ DumpCtx._TYPE_MAP[int] = DumpCtx._dumpPrimitive
466
+ DumpCtx._TYPE_MAP[float] = DumpCtx._dumpPrimitive
467
+ DumpCtx._TYPE_MAP[bool] = DumpCtx._dumpPrimitive
468
+ DumpCtx._TYPE_MAP[str] = DumpCtx._dumpPrimitive
469
+ DumpCtx._TYPE_MAP[_Omitted] = DumpCtx._dumpOmitted
470
+
471
+
472
+
473
+
474
+
475
+
476
+ class Dumper(object):
477
+
478
+ def __init__(self):
479
+ self.__outputLines = []
480
+ self.__contexts = []
481
+ self.__currentPrefix = ""
482
+ #
483
+
484
+ def createContext(self, obj, prefix:str = None):
485
+ if prefix is not None:
486
+ assert isinstance(prefix, str)
487
+ else:
488
+ prefix = ""
489
+
490
+ return DumpCtx(DEFAULT_DUMPER_SETTINGS, self.__outputLines, None, prefix)
491
+ #
492
+
493
+ def print(self, printFunc = None):
494
+ if printFunc is None:
495
+ printFunc = print
496
+ else:
497
+ assert callable(printFunc)
498
+
499
+ for line in self.__outputLines:
500
+ printFunc(line)
501
+ #
502
+
503
+ #
504
+
505
+
506
+
507
+
508
+
509
+ class DumpMixin:
510
+
511
+ def dump(self, prefix:str = None, printFunc = None):
512
+ dumper = Dumper()
513
+ with dumper.createContext(self, prefix) as dumper2:
514
+ if not dumper2._isDumpableObj(self):
515
+ raise Exception("Improper object encountered for prettyprinting: " + self.__class__.__name__ + " - Either implement _dump(ctx:DumpCtx) or _dumpVarNames()!")
516
+ dumper2._dumpObj("", self)
517
+ dumper.print(printFunc)
518
+ #
519
+
520
+ #
521
+
522
+
523
+
524
+
525
+
526
+
527
+
528
+
529
+
530
+
531
+
532
+
@@ -0,0 +1,54 @@
1
+ Metadata-Version: 2.1
2
+ Name: jk-prettyprintobj
3
+ Version: 0.2021.1.4
4
+ Summary: This python module provides a mixin for creating pretty debugging output for objects. This is especially useful for semi-complex data structures.
5
+ Home-page: UNKNOWN
6
+ Author: Jürgen Knauth
7
+ Author-email: pubsrc@binary-overflow.de
8
+ License: Apache2
9
+ Description: jk_prettyprintobj
10
+ ========
11
+
12
+ Introduction
13
+ ------------
14
+
15
+ This python module provides a mixin for dumping objects.
16
+
17
+ Information about this module can be found here:
18
+
19
+ * [github.org](https://github.com/jkpubsrc/python-module-jk-prettyprintobj)
20
+ * [pypi.python.org](https://pypi.python.org/pypi/jk_prettyprintobj)
21
+
22
+ How to use this module
23
+ ----------------------
24
+
25
+ ### ....
26
+
27
+ ....
28
+
29
+ Contact Information
30
+ -------------------
31
+
32
+ This is Open Source code. That not only gives you the possibility of freely using this code it also
33
+ allows you to contribute. Feel free to contact the author(s) of this software listed below, either
34
+ for comments, collaboration requests, suggestions for improvement or reporting bugs:
35
+
36
+ * Jürgen Knauth: pubsrc@binary-overflow.de
37
+
38
+ License
39
+ -------
40
+
41
+ This software is provided under the following license:
42
+
43
+ * Apache Software License 2.0
44
+
45
+
46
+
47
+
48
+ Keywords: pretty-print,debugging,debug
49
+ Platform: UNKNOWN
50
+ Classifier: Development Status :: 5 - Production/Stable
51
+ Classifier: License :: OSI Approved :: Apache Software License
52
+ Classifier: Programming Language :: Python :: 3
53
+ Classifier: Topic :: Software Development :: Testing
54
+ Description-Content-Type: text/markdown
@@ -0,0 +1,13 @@
1
+ LICENSE.txt
2
+ MANIFEST.in
3
+ README.md
4
+ setup.py
5
+ jk_prettyprintobj/_Bits.py
6
+ jk_prettyprintobj/_Hex.py
7
+ jk_prettyprintobj/__init__.py
8
+ jk_prettyprintobj/dumper.py
9
+ jk_prettyprintobj.egg-info/PKG-INFO
10
+ jk_prettyprintobj.egg-info/SOURCES.txt
11
+ jk_prettyprintobj.egg-info/dependency_links.txt
12
+ jk_prettyprintobj.egg-info/not-zip-safe
13
+ jk_prettyprintobj.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ jk_prettyprintobj
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,45 @@
1
+ ################################################################################
2
+ ################################################################################
3
+ ###
4
+ ### This file is automatically generated. Do not change this file! Changes
5
+ ### will get overwritten! Change the source file for "setup.py" instead.
6
+ ### This is either 'packageinfo.json' or 'packageinfo.jsonc'
7
+ ###
8
+ ################################################################################
9
+ ################################################################################
10
+
11
+
12
+ from setuptools import setup
13
+
14
+ def readme():
15
+ with open("README.md", "r", encoding="UTF-8-sig") as f:
16
+ return f.read()
17
+
18
+ setup(
19
+ author = "Jürgen Knauth",
20
+ author_email = "pubsrc@binary-overflow.de",
21
+ classifiers = [
22
+ "Development Status :: 5 - Production/Stable",
23
+ "License :: OSI Approved :: Apache Software License",
24
+ "Programming Language :: Python :: 3",
25
+ "Topic :: Software Development :: Testing",
26
+ ],
27
+ description = "This python module provides a mixin for creating pretty debugging output for objects. This is especially useful for semi-complex data structures.",
28
+ include_package_data = False,
29
+ install_requires = [
30
+ ],
31
+ keywords = [
32
+ "pretty-print",
33
+ "debugging",
34
+ "debug",
35
+ ],
36
+ license = "Apache2",
37
+ name = "jk_prettyprintobj",
38
+ packages = [
39
+ "jk_prettyprintobj",
40
+ ],
41
+ version = "0.2021.1.4",
42
+ zip_safe = False,
43
+ long_description = readme(),
44
+ long_description_content_type="text/markdown",
45
+ )