35
35
"""
36
36
37
37
import collections as _collections
38
- import dataclasses as _dataclasses
39
- import re
40
38
import sys as _sys
41
39
import types as _types
42
40
from io import StringIO as _StringIO
@@ -54,29 +52,35 @@ def pprint(object, stream=None, indent=1, width=80, depth=None, *,
54
52
underscore_numbers = underscore_numbers )
55
53
printer .pprint (object )
56
54
55
+
57
56
def pformat (object , indent = 1 , width = 80 , depth = None , * ,
58
57
compact = False , sort_dicts = True , underscore_numbers = False ):
59
58
"""Format a Python object into a pretty-printed representation."""
60
59
return PrettyPrinter (indent = indent , width = width , depth = depth ,
61
60
compact = compact , sort_dicts = sort_dicts ,
62
61
underscore_numbers = underscore_numbers ).pformat (object )
63
62
63
+
64
64
def pp (object , * args , sort_dicts = False , ** kwargs ):
65
65
"""Pretty-print a Python object"""
66
66
pprint (object , * args , sort_dicts = sort_dicts , ** kwargs )
67
67
68
+
68
69
def saferepr (object ):
69
70
"""Version of repr() which can handle recursive data structures."""
70
71
return PrettyPrinter ()._safe_repr (object , {}, None , 0 )[0 ]
71
72
73
+
72
74
def isreadable (object ):
73
75
"""Determine if saferepr(object) is readable by eval()."""
74
76
return PrettyPrinter ()._safe_repr (object , {}, None , 0 )[1 ]
75
77
78
+
76
79
def isrecursive (object ):
77
80
"""Determine if object requires a recursive representation."""
78
81
return PrettyPrinter ()._safe_repr (object , {}, None , 0 )[2 ]
79
82
83
+
80
84
class _safe_key :
81
85
"""Helper function for key functions when sorting unorderable objects.
82
86
@@ -99,10 +103,12 @@ def __lt__(self, other):
99
103
return ((str (type (self .obj )), id (self .obj )) < \
100
104
(str (type (other .obj )), id (other .obj )))
101
105
106
+
102
107
def _safe_tuple (t ):
103
108
"Helper function for comparing 2-tuples"
104
109
return _safe_key (t [0 ]), _safe_key (t [1 ])
105
110
111
+
106
112
class PrettyPrinter :
107
113
def __init__ (self , indent = 1 , width = 80 , depth = None , stream = None , * ,
108
114
compact = False , sort_dicts = True , underscore_numbers = False ):
@@ -179,12 +185,15 @@ def _format(self, object, stream, indent, allowance, context, level):
179
185
max_width = self ._width - indent - allowance
180
186
if len (rep ) > max_width :
181
187
p = self ._dispatch .get (type (object ).__repr__ , None )
188
+ # Lazy import to improve module import time
189
+ from dataclasses import is_dataclass
190
+
182
191
if p is not None :
183
192
context [objid ] = 1
184
193
p (self , object , stream , indent , allowance , context , level + 1 )
185
194
del context [objid ]
186
195
return
187
- elif (_dataclasses . is_dataclass (object ) and
196
+ elif (is_dataclass (object ) and
188
197
not isinstance (object , type ) and
189
198
object .__dataclass_params__ .repr and
190
199
# Check dataclass has generated repr method.
@@ -197,9 +206,12 @@ def _format(self, object, stream, indent, allowance, context, level):
197
206
stream .write (rep )
198
207
199
208
def _pprint_dataclass (self , object , stream , indent , allowance , context , level ):
209
+ # Lazy import to improve module import time
210
+ from dataclasses import fields as dataclass_fields
211
+
200
212
cls_name = object .__class__ .__name__
201
213
indent += len (cls_name ) + 1
202
- items = [(f .name , getattr (object , f .name )) for f in _dataclasses . fields (object ) if f .repr ]
214
+ items = [(f .name , getattr (object , f .name )) for f in dataclass_fields (object ) if f .repr ]
203
215
stream .write (cls_name + '(' )
204
216
self ._format_namespace_items (items , stream , indent , allowance , context , level )
205
217
stream .write (')' )
@@ -291,6 +303,9 @@ def _pprint_str(self, object, stream, indent, allowance, context, level):
291
303
if len (rep ) <= max_width1 :
292
304
chunks .append (rep )
293
305
else :
306
+ # Lazy import to improve module import time
307
+ import re
308
+
294
309
# A list of alternating (non-space, space) strings
295
310
parts = re .findall (r'\S*\s*' , line )
296
311
assert parts
@@ -632,9 +647,11 @@ def _safe_repr(self, object, context, maxlevels, level):
632
647
rep = repr (object )
633
648
return rep , (rep and not rep .startswith ('<' )), False
634
649
650
+
635
651
_builtin_scalars = frozenset ({str , bytes , bytearray , float , complex ,
636
652
bool , type (None )})
637
653
654
+
638
655
def _recursion (object ):
639
656
return ("<Recursion on %s with id=%s>"
640
657
% (type (object ).__name__ , id (object )))
0 commit comments