Try95th

prettyPrint - prettifyObj

Feb 21st, 2023
122
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.18 KB | None | 0 0
  1. def prettifyObj(obj, indent=2, curDepth=0, maxDepth=None):
  2.     if not isinstance(curDepth, int) or curDepth<0: curDepth = 0
  3.     if not isinstance(indent, str):
  4.         indent = ' '*(indent if isinstance(indent, int) and indent>0 else 2)
  5.     if not indent or (isinstance(maxDepth, int) and not curDepth<maxDepth):
  6.         return repr(obj)    
  7.     if not (obj and isinstance(obj, (list,set,tuple,dict))): return repr(obj)
  8.    
  9.     if isinstance(obj, dict):
  10.         b1, b2 = '{', '}'
  11.         unbraced = [(
  12.             f'{indent*(curDepth+1)}{repr(k)}: ' +
  13.             prettifyObj(v, indent, curDepth+1, maxDepth).strip()
  14.         ) for k, v in obj.items()]
  15.     else:
  16.         if isinstance(obj, list): b1, b2 = '[', ']'
  17.         elif isinstance(obj, set): b1, b2 = '{', '}'
  18.         elif isinstance(obj, tuple): b1, b2 = '(', ')'
  19.         unbraced = [(
  20.             indent*(curDepth+1) +
  21.             prettifyObj(v, indent, curDepth+1, maxDepth).strip()
  22.         ) for v in obj]
  23.  
  24.     b1, b2 = f'{indent*curDepth}{b1}\n', f'\n{indent*curDepth}{b2}'
  25.  
  26.     return b1 + ',\n'.join(unbraced) + b2
  27.  
  28. def prettyPrint(obj, pFunc=prettifyObj, *pargs, **pwargs):
  29.     print(pFunc(obj, *pargs, **pwargs))
Advertisement
Add Comment
Please, Sign In to add comment