[client] pylint and spell cleanup

Should have no functional change.

Change-Id: I8bda6f1750652daf214535a96c6aec65762e9960
Reviewed-on: https://chromium-review.googlesource.com/c/infra/luci/luci-py/+/1532600
Reviewed-by: Jao-ke Chin-Lee <jchinlee@chromium.org>
Commit-Queue: Marc-Antoine Ruel <maruel@chromium.org>
Cr-Mirrored-From: https://chromium.googlesource.com/infra/luci/luci-py
Cr-Mirrored-Commit: 4e2fb89c1f9a71c90b209bfa8b3a8a096c5515ea
diff --git a/auth.py b/auth.py
index c0a0279..a1e9791 100755
--- a/auth.py
+++ b/auth.py
@@ -123,9 +123,8 @@
   if service.login(True):
     print 'Logged in as \'%s\'.' % service.get_current_identity()
     return 0
-  else:
-    print 'Login failed or canceled.'
-    return 1
+  print 'Login failed or canceled.'
+  return 1
 
 
 @subcommand.usage('[options]')
diff --git a/isolate.py b/isolate.py
index 72bdff3..01ae5ad 100755
--- a/isolate.py
+++ b/isolate.py
@@ -114,7 +114,7 @@
         if metadata['s'] == fs.stat(outfile).st_size:
           continue
         else:
-          logging.warn('Overwritting %s' % metadata['h'])
+          logging.warn('Overwriting %s' % metadata['h'])
           fs.remove(outfile)
     else:
       outfile = os.path.join(outdir, relfile)
@@ -406,7 +406,7 @@
       if self.relative_cwd:
         # Only set relative_cwd if a command was also specified. This reduce the
         # noise for Swarming tasks where the command is specified as part of the
-        # Swarming task request and not thru the isolated file.
+        # Swarming task request and not through the isolated file.
         out['relative_cwd'] = self.relative_cwd
     return out
 
@@ -426,8 +426,9 @@
     """
     out = super(SavedState, cls).load(data, algo_name, isolated_basedir)
     if data.get('OS') != sys.platform:
-      raise isolated_format.IsolatedError('Unexpected OS %s', data.get('OS'))
+      raise isolated_format.IsolatedError('Unexpected OS %s' % data.get('OS'))
 
+    # pylint: disable=no-member
     # Converts human readable form back into the proper class type.
     algo = data.get('algo')
     if not algo in isolated_format.SUPPORTED_ALGOS:
@@ -446,7 +447,7 @@
           'Unsupported version \'%s\'' % out.version)
 
     # The .isolate file must be valid. If it is not present anymore, zap the
-    # value as if it was not noted, so .isolate_file can safely be overriden
+    # value as if it was not noted, so .isolate_file can safely be overridden
     # later.
     if out.isolate_file and not fs.isfile(out.isolate_filepath):
       out.isolate_file = None
diff --git a/isolateserver.py b/isolateserver.py
index ace3a1c..a518914 100755
--- a/isolateserver.py
+++ b/isolateserver.py
@@ -125,7 +125,7 @@
   """
   name = getattr(fileobj, 'name', None)
   if name is None:
-    return
+    return None
 
   # If the file like object was created using something like open("test.txt")
   # name will end up being a str (such as a function outside our control, like
@@ -138,10 +138,11 @@
   # fs.exists requires an absolute path, otherwise it will fail with an
   # assertion error.
   if not os.path.isabs(name):
-      return
+      return None
 
   if fs.exists(name):
     return name
+  return None
 
 
 # TODO(tansell): Replace fileobj_copy with shutil.copyfileobj once proper file
@@ -1711,6 +1712,7 @@
     return auth.ensure_logged_in(options.isolate_server)
   except ValueError as e:
     parser.error(str(e))
+  return None
 
 
 def add_cache_options(parser):
@@ -1755,8 +1757,7 @@
     # instance is created.
     return local_caching.DiskContentAddressedCache(
         unicode(os.path.abspath(options.cache)), policies, trim, **kwargs)
-  else:
-    return local_caching.MemoryContentAddressedCache()
+  return local_caching.MemoryContentAddressedCache()
 
 
 class OptionParserIsolateServer(logging_utils.OptionParserWithLogging):
diff --git a/run_isolated.py b/run_isolated.py
index 4022467..6228c1b 100755
--- a/run_isolated.py
+++ b/run_isolated.py
@@ -93,7 +93,7 @@
 # Use short names for temporary directories. This is driven by Windows, which
 # imposes a relatively short maximum path length of 260 characters, often
 # referred to as MAX_PATH. It is relatively easy to create files with longer
-# path length. A use case is with recursive depedency treesV like npm packages.
+# path length. A use case is with recursive dependency trees like npm packages.
 #
 # It is recommended to start the script with a `root_dir` as short as
 # possible.
@@ -861,6 +861,7 @@
 
   # Marshall into old-style inline output.
   if result['outputs_ref']:
+    # pylint: disable=unsubscriptable-object
     data = {
       'hash': result['outputs_ref']['isolated'],
       'namespace': result['outputs_ref']['namespace'],
diff --git a/swarming.py b/swarming.py
index 3df926f..c3de2e7 100755
--- a/swarming.py
+++ b/swarming.py
@@ -724,13 +724,12 @@
         tag_footer2,
         dash_pad,
         ])
-  else:
-    return '\n'.join([
-        dash_pad,
-        tag_header,
-        tag_footer2,
-        dash_pad,
-        ])
+  return '\n'.join([
+      dash_pad,
+      tag_header,
+      tag_footer2,
+      dash_pad,
+      ])
 
 
 def collect(
@@ -1235,7 +1234,7 @@
         *args,
         choices=self.choices,
         default=['console', 'json'],
-        help=re.sub('\s\s*', ' ', self.__doc__),
+        help=re.sub(r'\s\s*', ' ', self.__doc__),
         **kw)
 
   def convert_value(self, opt, value):
@@ -1595,6 +1594,8 @@
       print '  ' + api['description'].strip()
       if 'resources' in api:
         # Old.
+        # TODO(maruel): Remove.
+        # pylint: disable=too-many-nested-blocks
         for j, (resource_name, resource) in enumerate(
             sorted(api['resources'].iteritems())):
           if j:
diff --git a/tools/debug_task.py b/tools/debug_task.py
index 7b263a9..ec83546 100755
--- a/tools/debug_task.py
+++ b/tools/debug_task.py
@@ -89,8 +89,8 @@
     try:
       cmd = [
         sys.executable, 'isolateserver.py', 'download',
-        '-I',  task['properties']['inputs_ref']['isolatedserver'],
-        '--namespace',  task['properties']['inputs_ref']['namespace'],
+        '-I', task['properties']['inputs_ref']['isolatedserver'],
+        '--namespace', task['properties']['inputs_ref']['namespace'],
         '-f', isolated, name,
       ]
       subprocess.check_call(cmd, cwd=CLIENT_DIR)
@@ -133,8 +133,8 @@
     cmd.extend(
         [
           '-s', task['properties']['inputs_ref']['isolated'],
-          '-I',  task['properties']['inputs_ref']['isolatedserver'],
-          '--namespace',  task['properties']['inputs_ref']['namespace'],
+          '-I', task['properties']['inputs_ref']['isolatedserver'],
+          '--namespace', task['properties']['inputs_ref']['namespace'],
         ])
 
   for i in task['properties'].get('env', []):
diff --git a/tools/isolateserver_load_test.py b/tools/isolateserver_load_test.py
index 4bbe223..d6ae066 100755
--- a/tools/isolateserver_load_test.py
+++ b/tools/isolateserver_load_test.py
@@ -32,6 +32,8 @@
 
 # pylint: disable=ungrouped-imports
 import isolateserver
+import isolate_storage
+import isolated_format
 import local_caching
 from utils import graph
 from utils import threading_utils
@@ -137,7 +139,7 @@
     assert not expected, expected
 
     duration = max(0, time.time() - start)
-  except isolateserver.MappingError as e:
+  except isolated_format.MappingError as e:
     duration = str(e)
   if isinstance(duration, float):
     progress.update_item('', index=1, data=size)
@@ -214,7 +216,9 @@
 
   columns = [('index', 0), ('data', 0), ('size', options.items)]
   progress = Progress(columns)
-  storage = isolateserver.get_storage(options.isolate_server, options.namespace)
+  server_ref = isolate_storage.ServerRef(
+      options.isolate_server, options.namespace)
+  storage = isolateserver.get_storage(server_ref)
   do_item = functools.partial(
       send_and_receive,
       random_pool,
@@ -251,7 +255,7 @@
   print_results(results, options.columns, options.buckets)
   if options.dump:
     with open(options.dump, 'w') as f:
-      json.dump(results, f, separators=(',',':'))
+      json.dump(results, f, separators=(',', ':'))
   return 0
 
 
diff --git a/tools/parallel_execution.py b/tools/parallel_execution.py
index 2829537..2c50e82 100644
--- a/tools/parallel_execution.py
+++ b/tools/parallel_execution.py
@@ -109,6 +109,7 @@
           'Failed %s:\n%s' % (step_name, stdout), index=1)
       return (task_name, dimensions, stdout)
     self.progress.update_item('Passed %s' % step_name, index=1)
+    return None, None, None
 
 
 def run_swarming_tasks_parallel(
diff --git a/tools/swarming_load_test_bot.py b/tools/swarming_load_test_bot.py
index 71eeb38..40f4f94 100755
--- a/tools/swarming_load_test_bot.py
+++ b/tools/swarming_load_test_bot.py
@@ -327,7 +327,7 @@
   print_results(results, options.columns, options.buckets)
   if options.dump:
     with open(options.dump, 'w') as f:
-      json.dump(results, f, separators=(',',':'))
+      json.dump(results, f, separators=(',', ':'))
   return 0
 
 
diff --git a/tools/swarming_load_test_client.py b/tools/swarming_load_test_client.py
index 733cdb8..0642eda 100755
--- a/tools/swarming_load_test_client.py
+++ b/tools/swarming_load_test_client.py
@@ -74,6 +74,7 @@
   start = time.time()
 
   logging.info('trigger')
+  # TODO(maruel): Broken.
   manifest = swarming.Manifest(
     isolate_server='http://localhost:1',
     namespace='dummy-isolate',
@@ -100,7 +101,7 @@
     return 'failed_trigger'
 
   result = json.loads(response)
-  # Old API uses harcoded config name. New API doesn't have concept of config
+  # Old API uses hardcoded config name. New API doesn't have concept of config
   # name so it uses the task name. Ignore this detail.
   test_keys = []
   for key in result['test_keys']:
@@ -262,7 +263,7 @@
           if os.path.exists(options.dump):
             os.rename(options.dump, options.dump + '.old')
           with open(options.dump, 'wb') as f:
-            json.dump(results, f, separators=(',',':'))
+            json.dump(results, f, separators=(',', ':'))
       if not options.dump:
         results.sort()
     except KeyboardInterrupt:
diff --git a/tools/zip_profiler.py b/tools/zip_profiler.py
index ba8752d..c34c43e 100755
--- a/tools/zip_profiler.py
+++ b/tools/zip_profiler.py
@@ -103,7 +103,7 @@
     file_set = tree_files(temp_dir)
 
     if options.largest_files:
-      sorted_by_size = sorted(file_set.iteritems(),  key=lambda x: x[1],
+      sorted_by_size = sorted(file_set.iteritems(), key=lambda x: x[1],
                               reverse=True)
       files_to_compress = sorted_by_size[:options.largest_files]
 
diff --git a/trace_inputs.py b/trace_inputs.py
index aec6e3f..cd5de9f 100755
--- a/trace_inputs.py
+++ b/trace_inputs.py
@@ -64,7 +64,7 @@
 
 
 class TracingFailure(Exception):
-  """An exception occured during tracing."""
+  """An exception occurred during tracing."""
   def __init__(self, description, pid, line_number, line, *args):
     super(TracingFailure, self).__init__(
         description, pid, line_number, line, *args)
@@ -139,7 +139,7 @@
 def create_exec_thunk():
   """Creates a small temporary script to start the child executable.
 
-  Reads from the file handle provided as the fisrt argument to block, then
+  Reads from the file handle provided as the first argument to block, then
   execv() the command to be traced.
   """
   handle, name = tempfile.mkstemp(prefix=u'trace_inputs_thunk', suffix='.py')
@@ -173,16 +173,16 @@
   TODO(maruel): Implement escaping.
   """
   # All the possible states of the DFA.
-  ( NEED_QUOTE,         # Begining of a new arguments.
-    INSIDE_STRING,      # Inside an argument.
-    ESCAPED,            # Found a '\' inside a quote. Treat the next char as-is.
-    NEED_COMMA_OR_DOT,  # Right after the closing quote of an argument. Could be
-                        # a serie of 3 dots or a comma.
-    NEED_SPACE,         # Right after a comma
-    NEED_DOT_2,         # Found a dot, need a second one.
-    NEED_DOT_3,         # Found second dot, need a third one.
-    NEED_COMMA,         # Found third dot, need a comma.
-    ) = range(8)
+  (NEED_QUOTE,         # Beginning of a new arguments.
+   INSIDE_STRING,      # Inside an argument.
+   ESCAPED,            # Found a '\' inside a quote. Treat the next char as-is.
+   NEED_COMMA_OR_DOT,  # Right after the closing quote of an argument. Could be
+                       # a series of 3 dots or a comma.
+   NEED_SPACE,         # Right after a comma
+   NEED_DOT_2,         # Found a dot, need a second one.
+   NEED_DOT_3,         # Found second dot, need a third one.
+   NEED_COMMA,         # Found third dot, need a comma.
+   ) = range(8)
 
   state = NEED_QUOTE
   out = []
@@ -409,7 +409,7 @@
     """A file that was accessed. May not be present anymore.
 
     If tainted is true, it means it is not a real path anymore as a variable
-    replacement occured.
+    replacement occurred.
 
     |mode| can be one of None, TOUCHED, READ or WRITE.
     """
@@ -625,14 +625,14 @@
           """Receives a tuple (filepath, mode) and processes filepath."""
           x = fix_path(x)
           if not x:
-            return
+            return None, None
           # The blacklist needs to be reapplied, since path casing could
           # influence blacklisting.
           if self._blacklist(x):
-            return
+            return None, None
           # Filters out directories. Some may have passed through.
           if fs.isdir(x):
-            return
+            return None, None
           return x, m
 
         # Renders all the files as strings, as some could be RelativePath
@@ -641,7 +641,7 @@
         rendered = (
             fix_and_blacklist_path(f, m) for f, m in self.files.iteritems())
         files = sorted(
-          (f for f in rendered if f),
+          (f for f in rendered if f[0]),
           key=lambda x: (x[0], Results.File.ACCEPTABLE_MODES.index(x[1])))
         # Then converting into a dict will automatically clean up lesser
         # important values.
@@ -877,9 +877,9 @@
           assert function.__name__.startswith('handle_')
           def hook(self, args, result):
             if expect_zero is True and not result.startswith('0'):
-              return
+              return None
             if expect_zero is False and result.startswith(('?', '-1')):
-              return
+              return None
             match = re.match(regexp, args)
             if not match:
               raise TracingFailure(
@@ -965,19 +965,19 @@
 
           if self.RE_SIGNAL.match(line):
             # Ignore signals.
-            return
+            return None
 
           match = self.RE_KILLED.match(line)
           if match:
             # Converts a '+++ killed by Foo +++' trace into an exit_group().
             self.handle_exit_group(match.group(1), None)
-            return
+            return None
 
           match = self.RE_PROCESS_EXITED.match(line)
           if match:
             # Converts a '+++ exited with 1 +++' trace into an exit_group()
             self.handle_exit_group(match.group(1), None)
-            return
+            return None
 
           match = self.RE_UNFINISHED.match(line)
           if match:
@@ -988,7 +988,7 @@
                   self._pending_calls)
             self._pending_calls[match.group(1)] = (
                 match.group(1) + match.group(2))
-            return
+            return None
 
           match = self.RE_UNAVAILABLE.match(line)
           if match:
@@ -996,14 +996,14 @@
             # canceled.
             # TODO(maruel): Look up the last exit_group() trace just above and
             # make sure any self._pending_calls[anything] is properly flushed.
-            return
+            return None
 
           match = self.RE_PTRACE.match(line)
           if match:
             # Not sure what this means. Anyhow, the process died.
             # TODO(maruel): Add note that only RE_PROCESS_EXITED is valid
             # afterward.
-            return
+            return None
 
           match = self.RE_RESUMED.match(line)
           if match:
@@ -1023,10 +1023,10 @@
             # No other line can be processed afterward.
             logging.debug('%d is done: %s', self.pid, line)
             self._done = True
-            return
+            return None
 
           if match.group(1) == self.UNNAMED_FUNCTION:
-            return
+            return None
 
           # It's a valid line, handle it.
           handler = getattr(self, 'handle_%s' % match.group(1), None)
@@ -1188,7 +1188,7 @@
 
       @parse_args(
           r'^(\".+?\"|0x[a-f0-9]+), (?:\".+?\"(?:\.\.\.)?|0x[a-f0-9]+), '
-            '\d+$',
+            r'\d+$',
           False)
       def handle_readlink(self, args, _result):
         # TODO(maruel): Resolve file handle.
@@ -1831,7 +1831,7 @@
       text = text[:-2]
 
       def unescape(x):
-        """Replaces '\\' with '\' and '\?' (where ? is anything) with ?."""
+        """Replaces '\\\\' with '\\' and '\\?' (where ? is anything) with ?."""
         out = []
         escaped = False
         for i in x:
@@ -1886,7 +1886,7 @@
     #   in the associative array.
     # 1 is for tracked processes.
     # 2 is for the script created by create_subprocess_thunk() only. It is not
-    #   tracked itself but all its decendants are.
+    #   tracked itself but all its descendants are.
     #
     # The script will kill itself only once waiting_to_die == 1 and
     # current_processes == 0, so that both getlogin() was called and that
@@ -2344,7 +2344,7 @@
         fs.remove(self._dummy_file_name)
 
     def post_process_log(self):
-      """Sorts the log back in order when each call occured.
+      """Sorts the log back in order when each call occurred.
 
       dtrace doesn't save the buffer in strict order since it keeps one buffer
       per CPU.
@@ -2505,12 +2505,12 @@
       tid = int(tid, 16)
       pid = self._threads_active.get(tid)
       if not pid or not self._process_lookup.get(pid):
-        return
+        return None
       return self._process_lookup[pid]
 
     @classmethod
     def handle_EventTrace_Header(cls, line):
-      """Verifies no event was dropped, e.g. no buffer overrun occured."""
+      """Verifies no event was dropped, e.g. no buffer overrun occurred."""
       BUFFER_SIZE = cls.USER_DATA
       #VERSION = cls.USER_DATA + 1
       #PROVIDER_VERSION = cls.USER_DATA + 2
@@ -2535,8 +2535,8 @@
       #LOG_FILE_NAME_STRING = cls.USER_DATA + 21
       if line[EVENTS_LOST] != '0':
         raise TracingFailure(
-            ( '%s events were lost during trace, please increase the buffer '
-              'size from %s') % (line[EVENTS_LOST], line[BUFFER_SIZE]),
+            ('%s events were lost during trace, please increase the buffer '
+             'size from %s') % (line[EVENTS_LOST], line[BUFFER_SIZE]),
             None, None, None)
 
     def handle_FileIo_Cleanup(self, line):
@@ -2602,7 +2602,7 @@
         return
       # Override any stale file object.
       # TODO(maruel): Figure out a way to detect if the file was opened for
-      # reading or writting. Sadly CREATE_OPTIONS doesn't seem to be of any help
+      # reading or writing. Sadly CREATE_OPTIONS doesn't seem to be of any help
       # here. For now mark as None to make it clear we have no idea what it is
       # about.
       proc.file_objects[file_object] = (filepath, None)
@@ -2656,8 +2656,8 @@
         # TODO(maruel): The check is quite weak. Add the thunk path.
         if self._thunk_process:
           raise TracingFailure(
-              ( 'Parent process is _thunk_pid(%d) but thunk_process(%d) is '
-                'already set') % (self._thunk_pid, self._thunk_process.pid),
+              ('Parent process is _thunk_pid(%d) but thunk_process(%d) is '
+               'already set') % (self._thunk_pid, self._thunk_process.pid),
               None, None, None)
         proc = self.Process(self.blacklist, pid, None)
         self._thunk_process = proc
@@ -2725,7 +2725,7 @@
 
     @classmethod
     def supported_events(cls):
-      """Returns all the procesed events."""
+      """Returns all the processed events."""
       out = []
       for member in dir(cls):
         match = re.match(r'^handle_([A-Za-z]+)_([A-Za-z]+)$', member)
@@ -2776,24 +2776,24 @@
       """
         # 0. Had a ',' or one of the following ' ' after a comma, next should
         # be ' ', '"' or string or ',' for an empty field.
-      ( HAD_DELIMITER,
-        # 1. Processing an unquoted field up to ','.
-        IN_STR,
-        # 2. Processing a new field starting with '"'.
-        STARTING_STR_QUOTED,
-        # 3. Second quote in a row at the start of a field. It could be either
-        # '""foo""' or '""'. Who the hell thought it was a great idea to use
-        # the same character for delimiting and escaping?
-        STARTING_SECOND_QUOTE,
-        # 4. A quote inside a quoted string where the previous character was
-        # not a quote, so the string is not empty. Can be either: end of a
-        # quoted string (a delimiter) or a quote escape. The next char must be
-        # either '"' or ','.
-        HAD_QUOTE_IN_QUOTED,
-        # 5. Second quote inside a quoted string.
-        HAD_SECOND_QUOTE_IN_A_ROW_IN_QUOTED,
-        # 6. Processing a field that started with '"'.
-        IN_STR_QUOTED) = range(7)
+      (HAD_DELIMITER,
+       # 1. Processing an unquoted field up to ','.
+       IN_STR,
+       # 2. Processing a new field starting with '"'.
+       STARTING_STR_QUOTED,
+       # 3. Second quote in a row at the start of a field. It could be either
+       # '""foo""' or '""'. Who the hell thought it was a great idea to use
+       # the same character for delimiting and escaping?
+       STARTING_SECOND_QUOTE,
+       # 4. A quote inside a quoted string where the previous character was
+       # not a quote, so the string is not empty. Can be either: end of a
+       # quoted string (a delimiter) or a quote escape. The next char must be
+       # either '"' or ','.
+       HAD_QUOTE_IN_QUOTED,
+       # 5. Second quote inside a quoted string.
+       HAD_SECOND_QUOTE_IN_A_ROW_IN_QUOTED,
+       # 6. Processing a field that started with '"'.
+       IN_STR_QUOTED) = range(7)
 
       def __init__(self, f):
         self.f = f
@@ -3056,6 +3056,7 @@
                   None, None, None)
             continue
           # As you can see, the CSV is full of useful non-redundant information:
+          # pylint: disable=too-many-boolean-expressions
           if (line[2] != '0' or  # Event ID
               line[3] not in ('2', '3') or  # Version
               line[4] != '0' or  # Channel
@@ -3226,7 +3227,7 @@
   Arguments:
     - root_dir: Optional base directory that shouldn't be search further.
     - files: list of Results.File instances.
-    - blacklist: lambda to reject unneeded files, for example r'.+\.pyc'.
+    - blacklist: lambda to reject unneeded files, for example '.+\\.pyc'.
   """
   logging.info(
       'extract_directories(%s, %d files, ...)' % (root_dir, len(files)))
@@ -3437,7 +3438,7 @@
   def parse_args(self, *args, **kwargs):
     """Makes sure the paths make sense.
 
-    On Windows, / and \ are often mixed together in a path.
+    On Windows, / and \\ are often mixed together in a path.
     """
     options, args = logging_utils.OptionParserWithLogging.parse_args(
         self, *args, **kwargs)
diff --git a/utils/file_path.py b/utils/file_path.py
index 0b3a8d9..cdcf5fc 100644
--- a/utils/file_path.py
+++ b/utils/file_path.py
@@ -104,7 +104,7 @@
     chars = 1024
     drive_letter = drive_letter
     p = wintypes.create_unicode_buffer(chars)
-    if 0 == windll.kernel32.QueryDosDeviceW(drive_letter, p, chars):
+    if not windll.kernel32.QueryDosDeviceW(drive_letter, p, chars):
       err = ctypes.GetLastError()
       if err:
         # pylint: disable=undefined-variable
@@ -129,6 +129,7 @@
       msg = u'GetShortPathName(%s): %s (%d)' % (
             long_path, FormatError(err), err)
       raise WindowsError(err, msg.encode('utf-8'))
+    return None
 
 
   def GetLongPathName(short_path):
@@ -146,6 +147,7 @@
       msg = u'GetLongPathName(%s): %s (%d)' % (
             short_path, FormatError(err), err)
       raise WindowsError(err, msg.encode('utf-8'))
+    return None
 
 
   def MoveFileEx(oldpath, newpath, flags):
@@ -161,7 +163,7 @@
 
 
   class DosDriveMap(object):
-    """Maps \Device\HarddiskVolumeN to N: on Windows."""
+    """Maps \\Device\\HarddiskVolumeN to N: on Windows."""
     # Keep one global cache.
     _MAPPING = {}
 
@@ -353,7 +355,7 @@
   def enable_symlink():
     """Enable SeCreateSymbolicLinkPrivilege for the current token.
 
-    This funciton is only helpful in ONE of the following case:
+    This function is only helpful in ONE of the following case:
     - UAC is disabled, account is admin OR SeCreateSymbolicLinkPrivilege was
       manually granted.
     - UAC is enabled, account is NOT admin AND SeCreateSymbolicLinkPrivilege was
@@ -509,6 +511,7 @@
     for element in fs.listdir(root_path):
       if element.lower() == item:
         return element
+    return None
 
 
   @tools.profile
@@ -903,11 +906,12 @@
 
 
 def set_read_only_swallow(path, read_only):
-  """Returns if an OSError exception occured."""
+  """Returns if an OSError exception occurred."""
   try:
     set_read_only(path, read_only)
   except OSError as e:
     return e
+  return None
 
 
 def remove(filepath):
@@ -1013,7 +1017,7 @@
     else:
       # Flags are MOVEFILE_REPLACE_EXISTING|MOVEFILE_WRITE_THROUGH.
       MoveFileEx(unicode(tmp_name), unicode(path), 0x1|0x8)
-    tmp_name =  None # no need to remove it in 'finally' block anymore
+    tmp_name = None # no need to remove it in 'finally' block anymore
   finally:
     if tmp_name:
       try:
@@ -1180,6 +1184,7 @@
   # use or write to the directory while it is being deleted.
   max_tries = 3
   for i in xrange(max_tries):
+    # pylint: disable=cell-var-from-loop
     # errors is a list of tuple(function, path, excinfo).
     errors = []
     fs.rmtree(root, onerror=lambda *args: errors.append(args))
diff --git a/utils/net.py b/utils/net.py
index 21bb189..50078ed 100644
--- a/utils/net.py
+++ b/utils/net.py
@@ -159,7 +159,8 @@
     if isinstance(err, dict):
       return str(err.get('message') or '<no error message>')
   except (ValueError, KeyError, TypeError):
-    return None  # not a JSON we recognize
+    pass
+  return None  # not a JSON we recognize
 
 
 def set_engine_class(engine_cls):
@@ -646,8 +647,7 @@
     """Resource URL with url-encoded GET parameters."""
     if not self.params:
       return self.url
-    else:
-      return '%s?%s' % (self.url, urllib.urlencode(self.params))
+    return '%s?%s' % (self.url, urllib.urlencode(self.params))
 
 
 class HttpResponse(object):
diff --git a/utils/tools.py b/utils/tools.py
index 469ff61..1423118 100644
--- a/utils/tools.py
+++ b/utils/tools.py
@@ -295,7 +295,7 @@
   If dense is True, the json is packed. Otherwise, it is human readable.
   """
   if dense:
-    kwargs = {'sort_keys': True, 'separators': (',',':')}
+    kwargs = {'sort_keys': True, 'separators': (',', ':')}
   else:
     kwargs = {'sort_keys': True, 'indent': 2}