11# -*- coding: utf-8 -*-
2- # Copyright (C) 2009, 2013, 2015-2016, 2020 Rocky Bernstein
2+ # Copyright (C) 2009, 2013, 2015-2016, 2020-2021 Rocky Bernstein
33#
44# This program is free software: you can redistribute it and/or modify
55# it under the terms of the GNU General Public License as published by
1717import pprint
1818from columnize import columnize
1919
20+ # Maximum length of strings
21+ MAX_PP_STRLEN = 100
22+
23+ # Maximum number of keys in dictionary
24+ MAX_PP_COUNT = 20
25+
26+ # Maximum total formatted string
27+ MAX_PP_LENGTH = 2000
28+
29+
30+ def truncate_length (obj , length = MAX_PP_COUNT ):
31+ """If `obj` is something that has more than `length` items,
32+ then truncate it to the first `length` items.
33+ """
34+ if isinstance (obj , dict ):
35+ new_obj = dict ((k [:length ], v ) for k , v in sorted (obj .items ()))
36+ # We hope zzz will be appear at the end of the sorted list.
37+ new_obj .update ({"zzz..." : "..." })
38+ return new_obj
39+ elif hasattr (obj , "__getitem__" ):
40+ return list (obj [:length ]) + ["..." ]
41+ return obj
42+
43+
44+ class SafePP (pprint .PrettyPrinter ):
45+ def _format (self , obj , * args , ** kwargs ):
46+ if isinstance (obj , str ):
47+ if len (obj ) > MAX_PP_STRLEN :
48+ obj = obj [:MAX_PP_STRLEN ] + "..."
49+ pass
50+ pass
51+ elif hasattr (obj , "__len__" ) and len (obj ) > MAX_PP_COUNT :
52+ obj = truncate_length (obj )
53+
54+ return pprint .PrettyPrinter ._format (self , obj , * args , ** kwargs )
55+
2056
2157def pp (val , display_width , msg_nocr , msg , prefix = None ):
2258 if prefix is not None :
@@ -30,11 +66,11 @@ def pp(val, display_width, msg_nocr, msg, prefix=None):
3066 if isinstance (val , list ) or isinstance (val , tuple ):
3167 if not pprint_simple_array (val , display_width , msg_nocr , msg , " " ):
3268 print ("Can't print_simple_array" )
33- msg (" " + pprint .pformat (val ))
69+ msg (" " + pprint .pformat (val )[: MAX_PP_LENGTH ] )
3470 pass
3571 pass
3672 else :
37- msg (" " + pprint .pformat (val ))
73+ msg (" " + SafePP () .pformat (val )[: MAX_PP_LENGTH ] )
3874 pass
3975 return
4076
@@ -43,7 +79,7 @@ def pp(val, display_width, msg_nocr, msg, prefix=None):
4379# Possibly some will go into columnize.
4480def pprint_simple_array (val , displaywidth , msg_nocr , msg , lineprefix = "" ):
4581 """Try to pretty print a simple case where a list is not nested.
46- Return True if we can do it and False if not. """
82+ Return True if we can do it and False if not."""
4783
4884 if not (isinstance (val , list ) or isinstance (val , tuple )):
4985 return False
@@ -88,8 +124,8 @@ def msg(m):
88124 pp (x , 20 , msg_nocr , msg , "x = " )
89125 pp (x , 32 , msg_nocr , msg , "x = " )
90126 x = [i for i in range (30 )]
91- l = locals ().keys ()
92- for k in sorted (l ):
127+ ll = locals ().keys ()
128+ for k in sorted (ll ):
93129 pp (eval (k ), 80 , msg_nocr , msg , prefix = "%s =" % k )
94130 pass
95131 pass
0 commit comments