diff mbox

compress python code

Message ID 756bf9609cd741cb8b66a51f5abcd21f3eb4aff8.camel@aegee.org
State New
Headers show

Commit Message

Dilyan Palauzov Jan. 3, 2019, 8:35 p.m. UTC
Hello Simon,

in a former project I worked for, applied diverse regular expressions to rewrite the python code shorter, like

- X if X else Y → X or Y
- no else after return (unfold instead the code after return)

and applied the searches at that time to GDB (a year ago).

Regards
  Дилян

-------

    Compress Python code
    
    -- replace
         if x:
           return True
         return False
       with
         return x
       where x is boolean expression
    
    -- replace “if len(x) > 0…” with “if x…”
    
    -- replace “if len(x) != 0…” with “if x…”
    
    -- replace “if len(x) == 0…” with “if not x…”
    
    -- replace “if x not in y.keys():
                    y[x] = set()” with “y.setdefault(x, set())”
    
    -- remove “return” after “raise” (unreachable code)
    
    -- replace “if hasattr(x, 'y'):
                    return x.y
                return True" with “return getattr(x, y, True)”


On Thu, 2019-01-03 at 11:50 -0500, Simon Marchi wrote:
> On 2019-01-03 08:00, Дилян Палаузов wrote:
> > Some rewritings on python code, that make it shorter
> 
> Hi Dilyan,
> 
> Thanks for the patch.  I am fine with these changes, which use more 
> idiomatic Python constructs.  Did you hunt these occurrences by hand, or 
> did you use a static analysis tool/linter (if so, which one)?
> 
> In the commit log can you make a summary of the classes of changes you 
> do?  For example:
> 
> - Change "len(string) < 1" to "not string"
> - Change
> 
>      if string:
>        return False
>      return True
> 
>    to
> 
>      return not string
> - ...
> 
> 
> Finally, please include a corresponding ChangeLog entry, see [1] for 
> reference.  If it's not totally clear how to write it, do what you can 
> and I'll help you fix it after.
> 
> Simon
> 
> [1] 
> https://sourceware.org/gdb/wiki/ContributionChecklist#Properly_Formatted_GNU_ChangeLog
diff mbox

Patch

commit bdde2664e60259aeb0a9aa8715f9899672737f15
Author: Дилян Палаузов <git-dpa@aegee.org>
Date:   Thu Jan 3 17:27:44 2019 +0000

    Compress Python code
    
    -- replace
         if x:
           return True
         return False
       with
         return x
       where x is boolean expression
    
    -- replace “if len(x) > 0…” with “if x…”
    
    -- replace “if len(x) != 0…” with “if x…”
    
    -- replace “if len(x) == 0…” with “if not x…”
    
    -- replace “if x not in y.keys():
                    y[x] = set()” with “y.setdefault(x, set())”
    
    -- remove “return” after “raise” (unreachable code)
    
    -- replace “if hasattr(x, 'y'):
                    return x.y
                return True" with “return getattr(x, y, True)”

diff --git a/etc/ChangeLog b/etc/ChangeLog
index 78e9366e34..798b4f86a6 100644
--- a/etc/ChangeLog
+++ b/etc/ChangeLog
@@ -1,3 +1,7 @@ 
+2019-01-13  Дилян Палаузов  <dilyan.palauzov@aegee.org>
+
+	* update-copyright.py: compress
+
 2018-06-19  Simon Marchi  <simon.marchi@ericsson.com>
 
 	* configure.in: Remove AC_PREREQ.
diff --git a/etc/update-copyright.py b/etc/update-copyright.py
index 4579fcd8b1..6546c963b3 100755
--- a/etc/update-copyright.py
+++ b/etc/update-copyright.py
@@ -162,9 +162,7 @@  class GenericFilter:
         if filename in self.fossilised_files:
             return True
         # Only touch current current ChangeLogs.
-        if filename != 'ChangeLog' and filename.find ('ChangeLog') >= 0:
-            return True
-        return False
+        return filename != 'ChangeLog' and filename.find ('ChangeLog') >= 0:
 
     def by_package_author (self, dir, filename):
         return filename in self.own_files
diff --git a/gdb/ChangeLog b/gdb/ChangeLog
index 7d5fc4597d..f20e6c1e5a 100644
--- a/gdb/ChangeLog
+++ b/gdb/ChangeLog
@@ -1,3 +1,14 @@ 
+2019-01-03  Дилян Палаузов  <dilyan.palauzov@aegee.org>
+
+	* contrib/cleanup_check.py: compress
+	* contrib/test_pubnames_and_indexes.py: compress
+	* python/lib/gdb/FrameDecorator.py: compress
+	* python/lib/gdb/command/explore.py: compress
+	* python/lib/gdb/command/frame_filters.py: compress
+	* python/lib/gdb/command/pretty_printers.py: compress
+	* python/lib/gdb/frames.py: compress
+	* system-gdbinit/elinos.py: compress
+
 2019-01-03  Jim Wilson  <jimw@sifive.com>
 
 	* riscv-tdep.c (riscv_freg_feature): Drop s0 name from f8.
diff --git a/gdb/contrib/cleanup_check.py b/gdb/contrib/cleanup_check.py
index be6babbe94..89ed5b9b33 100644
--- a/gdb/contrib/cleanup_check.py
+++ b/gdb/contrib/cleanup_check.py
@@ -34,9 +34,7 @@  def is_cleanup_type(return_type):
         return False
     if not isinstance(return_type.dereference, gcc.RecordType):
         return False
-    if str(return_type.dereference.name) == 'cleanup':
-        return True
-    return False
+    return str(return_type.dereference.name) == 'cleanup'
 
 def is_constructor(decl):
     "Return True if the function DECL is a cleanup constructor; False otherwise"
@@ -130,7 +128,7 @@  class MasterCleanup(object):
             return True
         # If SELF is empty but OTHER has some cleanups, then consider
         # that a change as well.
-        if len(self.cleanups) == 0 and len(other.cleanups) > 0:
+        if not self.cleanups and other.cleanups:
             log('merging non-empty other', 4)
             self.cleanups = other.cleanups[:]
             return True
@@ -183,7 +181,7 @@  class MasterCleanup(object):
     # Check whether SELF is empty.
     def isempty(self):
         log('isempty: len = %d' % len(self.cleanups), 4)
-        return len(self.cleanups) == 0
+        return not self.cleanups
 
     # Emit informational warnings about the cleanup stack.
     def inform(self):
@@ -240,12 +238,11 @@  class CleanupChecker:
                     if not master_cleanup.verify(curloc, stmt.retval):
                         gcc.permerror(curloc,
                                       'constructor does not return master cleanup')
-                elif not self.is_special_constructor:
-                    if not master_cleanup.isempty():
-                        if curloc not in self.bad_returns:
-                            gcc.permerror(curloc, 'cleanup stack is not empty at return')
-                            self.bad_returns.add(curloc)
-                            master_cleanup.inform()
+                elif not self.is_special_constructor and not master_cleanup.isempty():
+                    if curloc not in self.bad_returns:
+                        gcc.permerror(curloc, 'cleanup stack is not empty at return')
+                        self.bad_returns.add(curloc)
+                        master_cleanup.inform()
 
     # Traverse a basic block, updating the master cleanup information
     # and propagating to other blocks.
diff --git a/gdb/contrib/test_pubnames_and_indexes.py b/gdb/contrib/test_pubnames_and_indexes.py
index 095fedd748..792e1724ee 100644
--- a/gdb/contrib/test_pubnames_and_indexes.py
+++ b/gdb/contrib/test_pubnames_and_indexes.py
@@ -64,7 +64,7 @@  def get_pub_info(filename, readelf_option):
         and fields[1].strip() == 'Name'):
       in_list = True
     # Either a blank-line or a new Length field terminates the current section.
-    elif (len(fields) == 0 or fields[0] == 'Length:'):
+    elif not fields or fields[0] == 'Length:':
       in_list = False;
     elif (in_list):
       pubnames.append(fields[1].strip())
@@ -95,11 +95,11 @@  def get_gdb_index(filename):
 def CheckSets(list0, list1, name0, name1):
   """Report any setwise differences between the two lists"""
 
-  if len(list0) == 0 or len(list1) == 0:
+  if not list0 or not list1:
     return False
 
   difference0 = set(list0) - set(list1)
-  if len(difference0) != 0:
+  if difference0:
     print "Elements in " + name0 + " but not " + name1 + ": (",
     print len(difference0),
     print ")"
@@ -107,14 +107,14 @@  def CheckSets(list0, list1, name0, name1):
       print "  " + element
 
   difference1 = set(list1) - set(list0)
-  if len(difference1) != 0:
+  if difference1:
     print "Elements in " + name1 + " but not " + name0 + ": (",
     print len(difference1),
     print ")"
     for element in difference1:
       print "  " + element
 
-  if (len(difference0) != 0 or len(difference1) != 0):
+  if not difference0 or not difference1:
     return True
 
   print name0 + " and " + name1 + " are identical."
@@ -182,15 +182,15 @@  def main(argv):
   pubs_list.sort()
 
   # Find the differences between the various indices.
-  if len(gold_index) == 0:
+  if not gold_index:
     print "Gold index is empty"
     failed |= True
 
-  if len(gdb_index) == 0:
+  if not gdb_index:
     print "Gdb index is empty"
     failed |= True
 
-  if len(pubs_list) == 0:
+  if not pubs_list:
     print "Pubs list is empty"
     failed |= True
 
diff --git a/gdb/python/lib/gdb/FrameDecorator.py b/gdb/python/lib/gdb/FrameDecorator.py
index 4eba088126..d386f6a88e 100644
--- a/gdb/python/lib/gdb/FrameDecorator.py
+++ b/gdb/python/lib/gdb/FrameDecorator.py
@@ -66,13 +66,9 @@  class FrameDecorator(object):
         limited."""
         sal = frame.find_sal()
 
-        if (not sal.symtab or not sal.symtab.filename
+        return (not sal.symtab or not sal.symtab.filename
             or frame.type() == gdb.DUMMY_FRAME
-            or frame.type() == gdb.SIGTRAMP_FRAME):
-
-            return True
-
-        return False
+            or frame.type() == gdb.SIGTRAMP_FRAME)
 
     def elided(self):
         """Return any elided frames that this class might be
diff --git a/gdb/python/lib/gdb/command/explore.py b/gdb/python/lib/gdb/command/explore.py
index f782a9712b..f724f58b59 100644
--- a/gdb/python/lib/gdb/command/explore.py
+++ b/gdb/python/lib/gdb/command/explore.py
@@ -521,7 +521,7 @@  class CompoundExplorer(object):
         CompoundExplorer._print_fields(print_list)
         print ("")
 
-        if len(choice_to_compound_field_map) > 0:
+        if choice_to_compound_field_map:
             choice = raw_input("Enter the field number of choice: ")
             if choice in choice_to_compound_field_map:
                 if is_child:
@@ -598,10 +598,9 @@  class ExploreUtils(object):
         Raises:
             gdb.GdbError if adequate arguments are not passed.
         """
-        if len(arg_str) < 1:
+        if not arg_str:
             raise gdb.GdbError("ERROR: '%s' requires an argument."
                                % name)
-            return False
         else:
             return True
 
diff --git a/gdb/python/lib/gdb/command/frame_filters.py b/gdb/python/lib/gdb/command/frame_filters.py
index 9d28f845b7..91cd0af73d 100644
--- a/gdb/python/lib/gdb/command/frame_filters.py
+++ b/gdb/python/lib/gdb/command/frame_filters.py
@@ -60,7 +60,7 @@  Usage: info frame-filters"""
                                       key=lambda i: gdb.frames.get_priority(i[1]),
                                       reverse=True)
 
-        if len(sorted_frame_filters) == 0:
+        if not sorted_frame_filters:
             return 0
 
         print(title)
diff --git a/gdb/python/lib/gdb/command/pretty_printers.py b/gdb/python/lib/gdb/command/pretty_printers.py
index c1bdf68fe0..de704cb6c1 100644
--- a/gdb/python/lib/gdb/command/pretty_printers.py
+++ b/gdb/python/lib/gdb/command/pretty_printers.py
@@ -75,10 +75,7 @@  def parse_printer_regexps(arg):
 
 def printer_enabled_p(printer):
     """Internal utility to see if printer (or subprinter) is enabled."""
-    if hasattr(printer, "enabled"):
-        return printer.enabled
-    else:
-        return True
+    return getattr(printer, "enabled", True)
 
 
 class InfoPrettyPrinter(gdb.Command):
diff --git a/gdb/python/lib/gdb/frames.py b/gdb/python/lib/gdb/frames.py
index d8e4be8d36..189da7e41a 100644
--- a/gdb/python/lib/gdb/frames.py
+++ b/gdb/python/lib/gdb/frames.py
@@ -179,7 +179,7 @@  def execute_frame_filters(frame, frame_low, frame_high):
 
     # Check to see if there are any frame-filters.  If not, just
     # return None and let default backtrace printing occur.
-    if len(sorted_list) == 0:
+    if not sorted_list:
         return None
 
     frame_iterator = FrameIterator(frame)
diff --git a/gdb/system-gdbinit/elinos.py b/gdb/system-gdbinit/elinos.py
index b303342c39..cbe4ab5143 100644
--- a/gdb/system-gdbinit/elinos.py
+++ b/gdb/system-gdbinit/elinos.py
@@ -83,7 +83,7 @@  def elinos_init():
             solib_dirs += ["%s/%s"
                            % (dir, "xenomai-build/usr/realtime/lib")]
 
-    if len(solib_dirs) != 0:
+    if solib_dirs:
         gdb.execute("set solib-search-path %s" % ":".join(solib_dirs))
 
 
diff --git a/gdb/testsuite/ChangeLog b/gdb/testsuite/ChangeLog
index 7c5ee11c6c..d1008b265b 100644
--- a/gdb/testsuite/ChangeLog
+++ b/gdb/testsuite/ChangeLog
@@ -1,3 +1,8 @@ 
+2019-01-03  Дилян Палаузов  <dilyan.palauzov@aegee.org>
+
+	* analyze-racy-logs.py: compress
+	* gdb.perf/lib/perftest/reporter.py: compress
+
 2018-12-28  Tom Tromey  <tom@tromey.com>
 	    Simon Marchi <simark@simark.ca>
 
diff --git a/gdb/testsuite/analyze-racy-logs.py b/gdb/testsuite/analyze-racy-logs.py
index 9036c9b789..c062927d69 100755
--- a/gdb/testsuite/analyze-racy-logs.py
+++ b/gdb/testsuite/analyze-racy-logs.py
@@ -72,8 +72,7 @@  dictionary referenced by DIC."""
         # Remove tail parentheses.  These are likely to be '(timeout)'
         # and other extra information that will only confuse us.
         test_name = re.sub ('(\s+)?\(.*$', '', test_name)
-        if result not in dic.keys ():
-            dic[result] = set ()
+        dic.setdefault(result, set ())
         if test_name in dic[result]:
             # If the line is already present in the dictionary, then
             # we include a unique identifier in the end of it, in the
diff --git a/gdb/testsuite/gdb.perf/lib/perftest/reporter.py b/gdb/testsuite/gdb.perf/lib/perftest/reporter.py
index 4fa242ebc5..edf494c0fb 100644
--- a/gdb/testsuite/gdb.perf/lib/perftest/reporter.py
+++ b/gdb/testsuite/gdb.perf/lib/perftest/reporter.py
@@ -62,7 +62,7 @@  class TextReporter(Reporter):
         self.txt_log = None
 
     def report(self, test_name, measurement_name, data_points):
-        if len(data_points) == 0:
+        if not data_points:
             self.txt_sum.write("%s %s *no data recorded*\n" % (
                 test_name, measurement_name))
             return