Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Misc Python smells from codefactor.io.
authorArnaud Giersch <arnaud.giersch@univ-fcomte.fr>
Tue, 22 Mar 2022 12:54:44 +0000 (13:54 +0100)
committerArnaud Giersch <arnaud.giersch@univ-fcomte.fr>
Tue, 22 Mar 2022 12:54:44 +0000 (13:54 +0100)
* unnecesary semicolon
* unnecessary "pass" statement.
* unnecessary "else" after "return".
* unnecessary "global"
* specify exception type
* testing for None should use the 'is' operator
* don't redefine built-ins
* unused statements (import, assignment)

docs/source/_ext/javasphinx/javasphinx/apidoc.py
docs/source/_ext/javasphinx/javasphinx/compiler.py
docs/source/_ext/javasphinx/javasphinx/domain.py
docs/source/_ext/javasphinx/javasphinx/formatter.py
docs/source/_ext/javasphinx/javasphinx/htmlrst.py
docs/source/_ext/javasphinx/javasphinx/util.py
teshsuite/s4u/monkey-masterworkers/monkey-masterworkers.py
teshsuite/smpi/MBI/MBIutils.py
teshsuite/smpi/MBI/simgrid.py
tools/simgrid-monkey

index b0de46f..c4eca15 100755 (executable)
@@ -18,7 +18,7 @@ from __future__ import print_function, unicode_literals
 
 try:
    import cPickle as pickle
-except:
+except ImportError:
    import pickle
 
 import hashlib
@@ -37,8 +37,7 @@ import javasphinx.util as util
 def encode_output(s):
    if isinstance(s, str):
       return s
-   else:
-      return s.encode('utf-8')
+   return s.encode('utf-8')
 
 def find_source_files(input_path, excludes):
     """ Get a list of filenames for all Java source files within the given
index 807d027..e4fe623 100644 (file)
@@ -98,12 +98,12 @@ class JavadocRestCompiler(object):
         if see.startswith('<a href'):
             # HTML link -- <a href="...">...</a>
             return self.__html_to_rst(see)
-        elif '"' in see:
+        if '"' in see:
             # Plain text
             return see
-        else:
-            # Type reference (default)
-            return ':java:ref:`%s`' % (see.replace('#', '.').replace(' ', ''),)
+
+        # Type reference (default)
+        return ':java:ref:`%s`' % (see.replace('#', '.').replace(' ', ''),)
 
     def compile_type(self, declaration):
         signature = util.StringBuilder()
index 275f6c8..5013c62 100644 (file)
@@ -132,9 +132,9 @@ class JavaObject(ObjectDescription):
                     parts.append(nodes.Text(dim, dim))
 
             return parts
-        else:
-            type_repr = formatter.output_type(typ).build()
-            return [nodes.Text(type_repr, type_repr)]
+
+        type_repr = formatter.output_type(typ).build()
+        return [nodes.Text(type_repr, type_repr)]
 
     def _build_type_node_list(self, types):
         parts = self._build_type_node(types[0])
@@ -149,10 +149,9 @@ class JavaObject(ObjectDescription):
 
         if handle:
             return handle(sig, signode)
-        else:
-            raise NotImplementedError
+        raise NotImplementedError
 
-    def get_index_text(self, package, type, name):
+    def get_index_text(self, package, typ, name):
         raise NotImplementedError
 
     def get_package(self):
@@ -163,9 +162,9 @@ class JavaObject(ObjectDescription):
 
     def add_target_and_index(self, name, sig, signode):
         package = self.get_package()
-        type = self.get_type();
+        typ = self.get_type()
 
-        fullname = '.'.join(filter(None, (package, type, name)))
+        fullname = '.'.join(filter(None, (package, typ, name)))
         basename = fullname.partition('(')[0]
 
         # note target
@@ -185,7 +184,7 @@ class JavaObject(ObjectDescription):
 
             objects[fullname] = (self.env.docname, self.objtype, basename)
 
-        indextext = self.get_index_text(package, type, name)
+        indextext = self.get_index_text(package, typ, name)
         if indextext:
             self.indexnode['entries'].append(_create_indexnode(indextext, fullname))
 
@@ -249,7 +248,7 @@ class JavaMethod(JavaObject):
         param_reprs = [formatter.output_type(param.type, with_generics=False).build() for param in member.parameters]
         return member.name + '(' + ', '.join(param_reprs) + ')'
 
-    def get_index_text(self, package, type, name):
+    def get_index_text(self, package, typ, name):
         return _('%s (Java method)' % (name,))
 
 class JavaConstructor(JavaObject):
@@ -289,7 +288,7 @@ class JavaConstructor(JavaObject):
         param_reprs = [formatter.output_type(param.type, with_generics=False).build() for param in member.parameters]
         return '%s(%s)' % (member.name, ', '.join(param_reprs))
 
-    def get_index_text(self, package, type, name):
+    def get_index_text(self, package, typ, name):
         return _('%s (Java constructor)' % (name,))
 
 class JavaType(JavaObject):
@@ -356,8 +355,8 @@ class JavaType(JavaObject):
 
         return member.name
 
-    def get_index_text(self, package, type, name):
-        return _('%s (Java %s)' % (name, self.declaration_type))
+    def get_index_text(self, package, typ, name):
+        return _('%s (Java %s)' % (name, self.declaration_typ))
 
 class JavaField(JavaObject):
     def handle_field_signature(self, sig, signode):
@@ -392,7 +391,7 @@ class JavaField(JavaObject):
 
         return declarator.name
 
-    def get_index_text(self, package, type, name):
+    def get_index_text(self, package, typ, name):
         return _('%s (Java field)' % (name,))
 
 class JavaPackage(Directive):
@@ -557,7 +556,7 @@ class JavaDomain(Domain):
         for fullname, (_, _, basename) in objects.items():
             if fullname.endswith(suffix):
                 return make_ref(fullname)
-            elif basename.endswith(basename_suffix):
+            if basename.endswith(basename_suffix):
                 basename_match = fullname
 
         if basename_match:
@@ -578,17 +577,15 @@ class JavaDomain(Domain):
         if ref:
             ref.append(contnode)
             return ref
-        else:
-            return None
+        return None
 
     def get_objects(self):
-        for refname, (docname, type, _) in self.data['objects'].items():
-            yield (refname, refname, type, docname, refname, 1)
+        for refname, (docname, typ, _) in self.data['objects'].items():
+            yield (refname, refname, typ, docname, refname, 1)
 
 
 def _create_indexnode(indextext, fullname):
     # See https://github.com/sphinx-doc/sphinx/issues/2673
     if version_info < (1, 4):
         return ('single', indextext, fullname, '')
-    else:
-        return ('single', indextext, fullname, '', None)
+    return ('single', indextext, fullname, '', None)
index 51b4ce7..ce6f6f5 100644 (file)
@@ -50,28 +50,28 @@ def output_annotation(annotation, output):
     output.append(' ')
 
 @formatter
-def output_type(type, output, with_generics=True):
-    if not type:
+def output_type(typ, output, with_generics=True):
+    if not typ:
         output.append('void')
         return
 
-    if type.dimensions:
-        dim = '[]' * len(type.dimensions)
+    if typ.dimensions:
+        dim = '[]' * len(typ.dimensions)
     else:
         dim = ''
 
-    if isinstance(type, javalang.tree.BasicType):
-        output.append(type.name)
+    if isinstance(typ, javalang.tree.BasicType):
+        output.append(typ.name)
     else:
-        while type:
-            output.append(type.name)
+        while typ:
+            output.append(typ.name)
 
             if with_generics:
-                output_type_args(type.arguments, output)
+                output_type_args(typ.arguments, output)
 
-            type = type.sub_type
+            typ = typ.sub_type
 
-            if type:
+            if typ:
                 output.append('.')
     output.append(dim)
 
index b34f1f2..687a034 100644 (file)
@@ -47,8 +47,7 @@ class Converter(object):
     def _unicode(self, s):
         if isinstance(s, unicode):
             return s
-        else:
-            return unicode(s, 'utf8')
+        return unicode(s, 'utf8')
 
     def _separate(self, s):
         return u'\n\n' + s + u'\n\n'
@@ -72,16 +71,14 @@ class Converter(object):
     def _role(self, role, s, label=None):
         if label:
             return self._escape_inline(':%s:`%s <%s>`' % (role, label, s))
-        else:
-            return self._escape_inline(':%s:`%s`' % (role, s))
+        return self._escape_inline(':%s:`%s`' % (role, s))
 
     def _directive(self, directive, body=None):
         header = '\n\n.. %s::\n\n' % (directive,)
 
         if body:
             return header + self._left_justify(body, 3) + '\n\n'
-        else:
-            return header + '\n'
+        return header + '\n'
 
     def _hyperlink(self, target, label):
         return self._escape_inline('`%s <%s>`_' % (label, target))
@@ -102,15 +99,14 @@ class Converter(object):
 
         if shift < 0:
             return '\n'.join(l[-shift:] for l in lines)
-        else:
-            prefix = ' ' * shift
-            return '\n'.join(prefix + l for l in lines)
+
+        prefix = ' ' * shift
+        return '\n'.join(prefix + l for l in lines)
 
     def _compress_whitespace(self, s, replace=' ', newlines=True):
         if newlines:
             return self._whitespace_with_newline.sub(replace, s)
-        else:
-            return self._whitespace.sub(replace, s)
+        return self._whitespace.sub(replace, s)
 
     # --------------------------------------------------------------------------
     # ---- DOM Tree Processing ----
@@ -269,16 +265,15 @@ class Converter(object):
         if node.name == 'a':
             if 'name' in node.attrs:
                 return self._separate('.. _' + node['name'] + ':')
-            elif 'href' in node.attrs:
+            if 'href' in node.attrs:
                 target = node['href']
                 label = self._compress_whitespace(self._process_text(node).strip('\n'))
 
                 if target.startswith('#'):
                     return self._role('ref', target[1:], label)
-                elif target.startswith('@'):
+                if target.startswith('@'):
                     return self._role('java:ref', target[1:], label)
-                else:
-                    return self._hyperlink(target, label)
+                return self._hyperlink(target, label)
 
         if node.name == 'ul':
             items = [self._process(n) for n in node.find_all('li', recursive=False)]
index 2de85d5..8e5f2a8 100644 (file)
@@ -30,8 +30,8 @@ class StringBuilder(list):
 
 class Directive(object):
 
-    def __init__(self, type, argument=''):
-        self.type = type
+    def __init__(self, typ, argument=''):
+        self.type = typ
         self.argument = argument
 
         self.options = []
index e8605f9..c9e92c7 100644 (file)
@@ -54,10 +54,10 @@ def master():
 
   assert False, "The impossible just happened (yet again): daemons shall not finish."
 
-def worker(id):
+def worker(my_id):
   global todo
-  this_actor.info(f"Worker {id} booting")
-  this_actor.on_exit(lambda killed: this_actor.info(f"Worker {id} dying {'forcefully' if killed else 'peacefully'}."))
+  this_actor.info(f"Worker {my_id} booting")
+  this_actor.on_exit(lambda killed: this_actor.info(f"Worker {my_id} dying {'forcefully' if killed else 'peacefully'}."))
 
   while todo > 0:
     assert Engine.clock < deadline, f"Failed to run all tasks in less than {deadline} seconds. Is this an infinite loop?"
@@ -78,7 +78,6 @@ def worker(id):
       this_actor.info("Timeouted while getting a task.")
 
 if __name__ == '__main__':
-  global mailbox
   e = Engine(sys.argv)
 
   assert host_count > 2, "You need at least 2 workers (i.e., 3 hosts) or the master will be auto-killed when the only worker gets killed."
index 070d321..59b22f8 100644 (file)
@@ -31,18 +31,18 @@ class AbstractTool:
         Ensure that this tool (previously built) is usable in this environment: setup the PATH, etc.
         This is called only once for all tests, from the logs directory.
         """
-        pass
+        pass
 
-    def run(execcmd, filename, binary, id, timeout):
+    def run(execcmd, filename, binary, num_id, timeout):
         """Compile that test code and anaylse it with the Tool if needed (a cache system should be used)"""
-        pass
+        pass
 
     def teardown(self):
         """
         Clean the results of all test runs: remove temp files and binaries.
         This is called only once for all tests, from the logs directory.
         """
-        pass
+        pass
 
     def parse(self, cachefile):
         """Read the result of a previous run from the cache, and compute the test outcome"""
@@ -105,10 +105,10 @@ def parse_one_code(filename):
     """
     res = []
     test_num = 0
-    with open(filename, "r") as input:
+    with open(filename, "r") as input_file:
         state = 0  # 0: before header; 1: in header; 2; after header
         line_num = 1
-        for line in input:
+        for line in input_file:
             if re.match(".*BEGIN_MBI_TESTS.*", line):
                 if state == 0:
                     state = 1
@@ -122,7 +122,7 @@ def parse_one_code(filename):
             if state == 1 and re.match("\s+\$ ?.*", line):
                 m = re.match('\s+\$ ?(.*)', line)
                 cmd = m.group(1)
-                nextline = next(input)
+                nextline = next(input_file)
                 detail = 'OK'
                 if re.match('[ |]*OK *', nextline):
                     expect = 'OK'
@@ -224,13 +224,12 @@ def run_cmd(buildcmd, execcmd, cachefile, filename, binary, timeout, batchinfo,
         if olddigest == newdigest:
             print(f" (result cached -- digest: {olddigest})")
             return False
-        else:
-            os.remove(f'{cachefile}.txt')
+        os.remove(f'{cachefile}.txt')
 
     print(f"Wait up to {timeout} seconds")
 
     start_time = time.time()
-    if buildcmd == None:
+    if buildcmd is None:
         output = f"No need to compile {binary}.c (batchinfo:{batchinfo})\n\n"
     else:
         output = f"Compiling {binary}.c (batchinfo:{batchinfo})\n\n"
index 8e39b13..aa2080a 100644 (file)
@@ -37,8 +37,8 @@ class Tool(AbstractTool):
         os.environ['PATH'] = os.environ['PATH'] + ":" + rootdir + "/builds/SimGrid/bin"
         os.environ['VERBOSE'] = '1'
 
-    def run(self, execcmd, filename, binary, id, timeout, batchinfo):
-        cachefile = f'{binary}_{id}'
+    def run(self, execcmd, filename, binary, num_id, timeout, batchinfo):
+        cachefile = f'{binary}_{num_id}'
 
         if not os.path.exists("cluster.xml"):
             with open('cluster.xml', 'w') as outfile:
index c48a771..8a70894 100755 (executable)
@@ -22,7 +22,6 @@
 #   * teshsuite/s4u/monkey-masterworkers: tests synchronous comms and execs (C++ and python)
 #   * teshsuite/s4u/monkey-semaphore: tests async semaphores (C++ only)
 
-import multiprocessing as mp
 import sys
 import os
 import argparse
@@ -111,7 +110,6 @@ def do_run(cmd, extra_params, test_todo):
 
 def doit():
     prev_time = 0
-    test_count = 0
     test_todo = 2 * len(timestamps) * (host_count + link_count)
     for pos in range(len(timestamps)):
         now = timestamps[pos]