Blob Blame Raw
From 20b6e154d08c41d4f06bcfb6393a7fd938fa6bcb Mon Sep 17 00:00:00 2001
From: Toshio Kuratomi <toshio@fedoraproject.org>
Date: Fri, 12 Dec 2014 09:10:50 -0800
Subject: [PATCH] Alternate pprint for values

As discussed in https://github.com/zestyping/q/pull/21 I've made some changes
to the pprint change proposed there.

* This will save long values into a separate file.

* This makes pprint of the variable the default.  I think this is a good idea
  because it will handle things like dicts nested within lists and other
  builtin types.
---
 q.py | 22 ++++++++++++++++++----
 1 file changed, 18 insertions(+), 4 deletions(-)

diff --git a/q.py b/q.py
index ceacd74..b461d6a 100644
--- a/q.py
+++ b/q.py
@@ -74,6 +74,7 @@ class Q(object):
     import inspect
     import os
     import pydoc
+    import pprint
     import sys
     import random
     import re
@@ -192,6 +193,13 @@ class Q(object):
             len(self.re.match(r'^ *', line).group()) for line in lines)
         return [line[indent:].rstrip() for line in lines]
 
+    def save_large_value(self, value):
+        if isinstance(value,  self.TEXT_TYPES):
+            value = value.encode('utf-8')
+        path = self.OUTPUT_PATH + '%08d.txt' % self.random.randrange(1e8)
+        self.FileWriter(path).write('w', value)
+        return path
+
     def safe_repr(self, value):
         # TODO: Use colour to distinguish '...' elision from actual '...'
         # TODO: Show a nicer repr for SRE.Match objects.
@@ -199,11 +207,17 @@ class Q(object):
         result = self.TEXT_REPR.repr(value)
         if isinstance(value, self.BASESTRING_TYPES) and len(value) > 80:
             # If the string is big, save it to a file for later examination.
-            if isinstance(value,  self.TEXT_TYPES):
-                value = value.encode('utf-8')
-            path = self.OUTPUT_PATH + '%08d.txt' % self.random.randrange(1e8)
-            self.FileWriter(path).write('w', value)
+            path = self.save_large_value(value)
             result += ' (file://' + path + ')'
+        else:
+            # Use pretty print if no specific choices were found
+            pp = self.pprint.PrettyPrinter(indent=1)
+            formatted = pp.pformat(value)
+            if len(formatted) > 80:
+                path = self.save_large_value(formatted)
+                result += ' (file://' + path + ')'
+            else:
+                result = formatted
         return result
 
     def get_call_exprs(self, line):
-- 
2.10.2