瀏覽代碼

Fix comparison, membership, indentation and lambda Flake8 warnings in scripts (#539)

* Test for membership should be 'not in' (Flake8 E713)
* Comparison to None should be 'if cond is None:' (Flake8 E711)
* Use ==/!= to compare str, bytes, and int literals (Flake8 F632)
* Comparison to True should be... (True cases for E712)
* Comparison to False should be 'if cond is False:' or 'if not cond:' (Flake8 E712)
* Indentation is not a multiple of four (Flake8 E111)
* Blank line at end of file (Flake8 W391)
* Do not assign a lambda expression, use a def (Flake8 E731)
* Remove one entry for disabled errors listed twice
Vaclav Petras 5 年之前
父節點
當前提交
6528264fc3

+ 0 - 14
scripts/.flake8

@@ -3,21 +3,11 @@ ignore =
     E265, # block comment should start with '# '
     E265, # block comment should start with '# '
     E266, # too many leading '#' for block comment
     E266, # too many leading '#' for block comment
     E402, # module level import not at top of file
     E402, # module level import not at top of file
-    E711, # comparison to None should be 'if cond is None:'
-    E712, # comparison to False should be 'if cond is False:' or 'if not cond:'
-    E713, # test for membership should be 'not in'
     E722, # do not use bare 'except'
     E722, # do not use bare 'except'
-    E731, # do not assign a lambda expression, use a def
     E741, # ambiguous variable name 'l'
     E741, # ambiguous variable name 'l'
     F401, # 'grass.script.core.gisenv' imported but unused
     F401, # 'grass.script.core.gisenv' imported but unused
-    F632, # use ==/!= to compare str, bytes, and int literals
     F821, # undefined name '_'
     F821, # undefined name '_'
     F841, # local variable 'center' is assigned to but never used
     F841, # local variable 'center' is assigned to but never used
-    E111, # indentation is not a multiple of four
-    E711, # comparison to None should be 'if cond is None:'
-    F632, # use ==/!= to compare str, bytes, and int literals
-    W391, # blank line at end of file
-    E111, # indentation is not a multiple of four
     E121, # continuation line under-indented for hanging indent
     E121, # continuation line under-indented for hanging indent
     E125, # continuation line with same indent as next logical line
     E125, # continuation line with same indent as next logical line
     E127, # continuation line over-indented for visual indent
     E127, # continuation line over-indented for visual indent
@@ -37,12 +27,8 @@ ignore =
     E305, # expected 2 blank lines after class or function definition, found 1
     E305, # expected 2 blank lines after class or function definition, found 1
     E501, # line too long (161 > 150 characters)
     E501, # line too long (161 > 150 characters)
     W293, # blank line contains whitespace
     W293, # blank line contains whitespace
-    W391, # blank line at end of file
     W503, # line break before binary operator
     W503, # line break before binary operator
     W504, # line break after binary operator
     W504, # line break after binary operator
-    E121, # continuation line under-indented for hanging indent
-    E221, # multiple spaces before operator
-    E251, # unexpected spaces around keyword / parameter equals
 
 
 max-line-length = 88
 max-line-length = 88
 exclude =
 exclude =

+ 4 - 2
scripts/g.extension/g.extension.py

@@ -966,7 +966,7 @@ def install_private_extension_xml(url, mlist):
                 tnode = node
                 tnode = node
                 break
                 break
 
 
-        if tnode == None:
+        if tnode is None:
             # create new node for task
             # create new node for task
             tnode = etree.Element('task', attrib={'name': name})
             tnode = etree.Element('task', attrib={'name': name})
             dnode = etree.Element('description')
             dnode = etree.Element('description')
@@ -1160,7 +1160,9 @@ def fix_newlines(directory):
     # skip binary files
     # skip binary files
     # see https://stackoverflow.com/a/7392391
     # see https://stackoverflow.com/a/7392391
     textchars = bytearray({7,8,9,10,12,13,27} | set(range(0x20, 0x100)) - {0x7f})
     textchars = bytearray({7,8,9,10,12,13,27} | set(range(0x20, 0x100)) - {0x7f})
-    is_binary_string = lambda bytes: bool(bytes.translate(None, textchars))
+
+    def is_binary_string(bytes):
+        return bool(bytes.translate(None, textchars))
 
 
     for root, unused, files in os.walk(directory):
     for root, unused, files in os.walk(directory):
         for name in files:
         for name in files:

+ 1 - 1
scripts/g.search.modules/g.search.modules.py

@@ -283,7 +283,7 @@ def _basic_search(pattern, name, description, module_keywords):
         if name.lower().find(pattern) > -1 or\
         if name.lower().find(pattern) > -1 or\
            description.lower().find(pattern) > -1 or\
            description.lower().find(pattern) > -1 or\
            module_keywords.lower().find(pattern) > -1:
            module_keywords.lower().find(pattern) > -1:
-           return True
+            return True
         else:
         else:
             return False
             return False
     else:
     else:

+ 1 - 1
scripts/i.oif/i.oif.py

@@ -102,7 +102,7 @@ def main():
         n = 0
         n = 0
         for band in bands:
         for band in bands:
             proc[band] = grass.pipe_command('r.univar', flags='g', map=band)
             proc[band] = grass.pipe_command('r.univar', flags='g', map=band)
-            if n % workers is 0:
+            if n % workers == 0:
                 # wait for the ones launched so far to finish
                 # wait for the ones launched so far to finish
                 for bandp in bands[:n]:
                 for bandp in bands[:n]:
                     if not proc[bandp].stdout.closed:
                     if not proc[bandp].stdout.closed:

+ 1 - 1
scripts/i.pansharpen/i.pansharpen.py

@@ -141,7 +141,7 @@ def main():
     ms3 = 'tmp%s_ms3' % pid
     ms3 = 'tmp%s_ms3' % pid
     pan = 'tmp%s_pan' % pid
     pan = 'tmp%s_pan' % pid
 
 
-    if rescale == False:
+    if not rescale:
         if bits == 8:
         if bits == 8:
             grass.message(_("Using 8bit image channels"))
             grass.message(_("Using 8bit image channels"))
             if sproc:
             if sproc:

+ 2 - 2
scripts/r.grow/r.grow.py

@@ -95,7 +95,7 @@ def main():
         shrink = True
         shrink = True
         radius = -radius
         radius = -radius
 
 
-    if new == '' and shrink == False:
+    if new == '' and not shrink:
         temp_val = "r.grow.tmp.%s.val" % tmp
         temp_val = "r.grow.tmp.%s.val" % tmp
         new = '"%s"' % temp_val
         new = '"%s"' % temp_val
     else:
     else:
@@ -127,7 +127,7 @@ def main():
     else:
     else:
         output = out_name[0]
         output = out_name[0]
 
 
-    if shrink is False:
+    if not shrink:
         try:
         try:
             grass.run_command('r.grow.distance', input=input, metric=metric,
             grass.run_command('r.grow.distance', input=input, metric=metric,
                               distance=temp_dist, value=temp_val)
                               distance=temp_dist, value=temp_val)

+ 1 - 1
scripts/r.in.srtm/r.in.srtm.py

@@ -161,7 +161,7 @@ def main():
     # are we in LatLong location?
     # are we in LatLong location?
     s = grass.read_command("g.proj", flags='j')
     s = grass.read_command("g.proj", flags='j')
     kv = grass.parse_key_val(s)
     kv = grass.parse_key_val(s)
-    if not '+proj' in kv.keys() or kv['+proj'] != 'longlat':
+    if '+proj' not in kv.keys() or kv['+proj'] != 'longlat':
         grass.fatal(_("This module only operates in LatLong locations"))
         grass.fatal(_("This module only operates in LatLong locations"))
 
 
     # use these from now on:
     # use these from now on:

+ 1 - 1
scripts/r.in.wms/r.in.wms.py

@@ -256,7 +256,7 @@ def main():
         if not fetched_map:
         if not fetched_map:
             grass.warning(_("Nothing to import.\nNo data has been downloaded from wms server."))
             grass.warning(_("Nothing to import.\nNo data has been downloaded from wms server."))
             return
             return
-        importer = GRASSImporter(options['output'], (flags['b'] == False))
+        importer = GRASSImporter(options['output'], (not flags['b']))
         importer.ImportMapIntoGRASS(fetched_map)
         importer.ImportMapIntoGRASS(fetched_map)
 
 
     return 0
     return 0

+ 3 - 3
scripts/r.in.wms/wms_base.py

@@ -89,7 +89,7 @@ class WMSBase(object):
         self.params['bgcolor'] = options['bgcolor'].strip()
         self.params['bgcolor'] = options['bgcolor'].strip()
 
 
         if options['format'] == "jpeg" and \
         if options['format'] == "jpeg" and \
-           not 'format' in driver_props['ignored_params']:
+           'format' not in driver_props['ignored_params']:
             if not flags['o'] and \
             if not flags['o'] and \
                     'WMS' in self.params['driver']:
                     'WMS' in self.params['driver']:
                 grass.warning(_("JPEG format does not support transparency"))
                 grass.warning(_("JPEG format does not support transparency"))
@@ -100,7 +100,7 @@ class WMSBase(object):
 
 
         # TODO: get srs from Tile Service file in OnEarth_GRASS driver
         # TODO: get srs from Tile Service file in OnEarth_GRASS driver
         self.params['srs'] = int(options['srs'])
         self.params['srs'] = int(options['srs'])
-        if self.params['srs'] <= 0 and not 'srs' in driver_props['ignored_params']:
+        if self.params['srs'] <= 0 and 'srs' not in driver_props['ignored_params']:
             grass.fatal(_("Invalid EPSG code %d") % self.params['srs'])
             grass.fatal(_("Invalid EPSG code %d") % self.params['srs'])
 
 
         self.params['wms_version'] = options['wms_version']
         self.params['wms_version'] = options['wms_version']
@@ -380,7 +380,7 @@ class WMSBase(object):
             and self.source_epsg == self.target_epsg:
             and self.source_epsg == self.target_epsg:
             do_reproject = False
             do_reproject = False
         # TODO: correctly compare source and target crs
         # TODO: correctly compare source and target crs
-        if do_reproject == True and self.proj_srs == self.proj_location:
+        if do_reproject and self.proj_srs == self.proj_location:
             do_reproject = False
             do_reproject = False
         if do_reproject:
         if do_reproject:
             grass.message(_("Reprojecting raster..."))
             grass.message(_("Reprojecting raster..."))

+ 1 - 1
scripts/r.in.wms/wms_cap_parsers.py

@@ -83,7 +83,7 @@ class WMSCapabilitiesTree(BaseCapabilitiesTree):
 
 
         grass.debug('Checking WMS capabilities tree.', 4)
         grass.debug('Checking WMS capabilities tree.', 4)
 
 
-        if not "version" in self.getroot().attrib:
+        if "version" not in self.getroot().attrib:
             raise ParseError(_("Missing version attribute root node "
             raise ParseError(_("Missing version attribute root node "
                                "in Capabilities XML file"))
                                "in Capabilities XML file"))
         else:
         else:

+ 1 - 1
scripts/r.in.wms/wms_drv.py

@@ -843,7 +843,7 @@ class OnEarthRequestMgr(BaseRequestMgr):
         else:
         else:
             url = urls[0]
             url = urls[0]
             for u in urls:
             for u in urls:
-                if not 'time=${' in u:
+                if 'time=${' not in u:
                     url = u
                     url = u
 
 
         url, t_bbox, width, height = self.cap_tree.gettilepatternurldata(url)
         url, t_bbox, width, height = self.cap_tree.gettilepatternurldata(url)

+ 0 - 1
scripts/r.mapcalc.simple/r.mapcalc.simple.py

@@ -147,4 +147,3 @@ def main():
 
 
 if __name__ == "__main__":
 if __name__ == "__main__":
     sys.exit(main())
     sys.exit(main())
-

+ 4 - 4
scripts/r3.in.xyz/r3.in.xyz.py

@@ -201,7 +201,7 @@ def main():
     shell_style = flags['g']
     shell_style = flags['g']
     ignore_broken = flags['i']
     ignore_broken = flags['i']
 
 
-    if workers is 1 and "WORKERS" in os.environ:
+    if workers == 1 and "WORKERS" in os.environ:
         workers = int(os.environ["WORKERS"])
         workers = int(os.environ["WORKERS"])
 
 
     if not os.path.exists(infile):
     if not os.path.exists(infile):
@@ -286,17 +286,17 @@ def main():
         grass.debug("i=%d, %%=%d  (workers=%d)" % (i, i % workers, workers))
         grass.debug("i=%d, %%=%d  (workers=%d)" % (i, i % workers, workers))
         # print sys.getsizeof(proc)  # sizeof(proc array)  [not so big]
         # print sys.getsizeof(proc)  # sizeof(proc array)  [not so big]
 
 
-        if i % workers is 0:
+        if i % workers == 0:
             # wait for the ones launched so far to finish
             # wait for the ones launched so far to finish
             for p_i in depths[:i]:
             for p_i in depths[:i]:
                 pout[p_i] = proc[p_i].communicate()[0]
                 pout[p_i] = proc[p_i].communicate()[0]
-                if proc[p_i].wait() is not 0:
+                if proc[p_i].wait() != 0:
                     grass.fatal(_("Trouble importing data. Aborting."))
                     grass.fatal(_("Trouble importing data. Aborting."))
 
 
     # wait for jSobs to finish, collect any stray output
     # wait for jSobs to finish, collect any stray output
     for i in depths:
     for i in depths:
         pout[i] = proc[i].communicate()[0]
         pout[i] = proc[i].communicate()[0]
-        if proc[i].wait() is not 0:
+        if proc[i].wait() != 0:
             grass.fatal(_("Trouble importing data. Aborting."))
             grass.fatal(_("Trouble importing data. Aborting."))
 
 
     del proc
     del proc

+ 2 - 2
scripts/v.db.addtable/v.db.addtable.py

@@ -110,7 +110,7 @@ def main():
                                 stderr=nuldev)
                                 stderr=nuldev)
     tables = decode(tables)
     tables = decode(tables)
 
 
-    if not table in tables.splitlines():
+    if table not in tables.splitlines():
         colnames = []
         colnames = []
         column_def = []
         column_def = []
         if columns:
         if columns:
@@ -123,7 +123,7 @@ def main():
                 column_def.append(x)
                 column_def.append(x)
 
 
         # if not existing, create it:
         # if not existing, create it:
-        if not key in colnames:
+        if key not in colnames:
             column_def.insert(0, "%s integer" % key)
             column_def.insert(0, "%s integer" % key)
         column_def = ','.join(column_def)
         column_def = ','.join(column_def)
 
 

+ 1 - 1
scripts/v.db.reconnect.all/v.db.reconnect.all.py

@@ -241,7 +241,7 @@ def main():
             if schema != old_schema:
             if schema != old_schema:
                 do_reconnect = False
                 do_reconnect = False
 
 
-            if do_reconnect == True:
+            if do_reconnect:
                 gscript.verbose(_("Reconnecting layer %d...") % layer)
                 gscript.verbose(_("Reconnecting layer %d...") % layer)
 
 
                 if flags['c']:
                 if flags['c']:

+ 1 - 1
scripts/v.import/v.import.py

@@ -153,7 +153,7 @@ def fix_gfsfile(input):
         tree = ET.parse(gfsfile)
         tree = ET.parse(gfsfile)
         root = tree.getroot()
         root = tree.getroot()
         gfsstring = ET.tostring(root).decode('utf-8')
         gfsstring = ET.tostring(root).decode('utf-8')
-        if not "srsname" in gfsstring.lower():
+        if "srsname" not in gfsstring.lower():
             for featClass in root.findall('GMLFeatureClass'):
             for featClass in root.findall('GMLFeatureClass'):
                 ET.SubElement(featClass, 'SRSName').text = srs_str
                 ET.SubElement(featClass, 'SRSName').text = srs_str
             tree.write(gfsfile)
             tree.write(gfsfile)