commit:     709826c0896120e8b3d9995d71678c0b9b290e4c
Author:     Alec Warner <antarus <AT> gentoo <DOT> org>
AuthorDate: Wed Jul 29 18:27:16 2020 +0000
Commit:     Zac Medico <zmedico <AT> gentoo <DOT> org>
CommitDate: Thu Jul 30 04:05:06 2020 +0000
URL:        https://gitweb.gentoo.org/proj/portage.git/commit/?id=709826c0

Fix R1705.

The codebase appears to have this pattern like:

if foo == bar:
  return a
elif foo == baz:
  return b
else:
  return c

This can often be rewritten as:
if foo == bar:
  return a
if foo == baz:
  return b
return c

Closes: https://github.com/gentoo/portage/pull/592
Signed-off-by: Alec Warner <antarus <AT> gentoo.org>
Signed-off-by: Zac Medico <zmedico <AT> gentoo.org>

 lib/_emerge/EbuildBuild.py                         |  24 ++--
 lib/_emerge/MergeListItem.py                       |   2 +-
 lib/_emerge/Package.py                             |   3 +-
 lib/_emerge/actions.py                             |  11 +-
 lib/_emerge/depgraph.py                            | 131 ++++++++++-----------
 lib/_emerge/main.py                                |   4 +-
 lib/_emerge/resolver/backtracking.py               |   3 +-
 lib/_emerge/resolver/output.py                     |  34 +++---
 lib/_emerge/resolver/slot_collision.py             |  32 +++--
 lib/_emerge/unmerge.py                             |   4 +-
 lib/portage/_emirrordist/FetchTask.py              |  36 +++---
 lib/portage/_global_updates.py                     |   3 +-
 lib/portage/_legacy_globals.py                     |   2 +-
 lib/portage/_sets/__init__.py                      |   7 +-
 lib/portage/_sets/base.py                          |   3 +-
 lib/portage/_sets/dbapi.py                         |  43 ++++---
 lib/portage/cache/ebuild_xattr.py                  |   3 +-
 lib/portage/cache/mappings.py                      |   4 +-
 lib/portage/cache/sqlite.py                        |   5 +-
 lib/portage/checksum.py                            |   2 +-
 lib/portage/cvstree.py                             |   5 +-
 lib/portage/data.py                                |   5 +-
 lib/portage/dbapi/IndexedPortdb.py                 |   3 +-
 lib/portage/dbapi/IndexedVardb.py                  |   3 +-
 lib/portage/dbapi/bintree.py                       |  14 +--
 lib/portage/dbapi/cpv_expand.py                    |   6 +-
 lib/portage/dbapi/porttree.py                      |   5 +-
 lib/portage/dbapi/vartree.py                       |   6 +-
 lib/portage/dbapi/virtual.py                       |   3 +-
 lib/portage/debug.py                               |  12 +-
 lib/portage/dep/__init__.py                        |  22 ++--
 lib/portage/dep/_dnf.py                            |   2 +-
 lib/portage/dep/dep_check.py                       |  13 +-
 lib/portage/elog/mod_mail_summary.py               |   2 +-
 lib/portage/exception.py                           |   3 +-
 lib/portage/getbinpkg.py                           |   8 +-
 lib/portage/glsa.py                                |   5 +-
 lib/portage/locks.py                               |  15 ++-
 lib/portage/manifest.py                            |   7 +-
 lib/portage/output.py                              |  30 +++--
 lib/portage/package/ebuild/_ipc/QueryCommand.py    |  15 ++-
 .../ebuild/_parallel_manifest/ManifestProcess.py   |   3 +-
 lib/portage/package/ebuild/config.py               |  17 ++-
 lib/portage/package/ebuild/doebuild.py             |   8 +-
 lib/portage/package/ebuild/fetch.py                |  10 +-
 lib/portage/package/ebuild/getmaskingreason.py     |   9 +-
 lib/portage/package/ebuild/getmaskingstatus.py     |   2 +-
 lib/portage/repository/config.py                   |   3 +-
 lib/portage/sync/controller.py                     |   3 +-
 lib/portage/sync/modules/git/git.py                |  33 +++---
 lib/portage/tests/util/futures/test_retry.py       |  12 +-
 lib/portage/util/__init__.py                       |  33 ++----
 lib/portage/util/_async/PipeLogger.py              |  89 +++++++-------
 lib/portage/util/_dyn_libs/LinkageMapELF.py        |  33 +++---
 lib/portage/util/_urlopen.py                       |  42 +++----
 lib/portage/util/changelog.py                      |  19 ++-
 lib/portage/util/futures/_asyncio/__init__.py      |   5 +-
 lib/portage/util/futures/unix_events.py            |   9 +-
 lib/portage/util/lafilefixer.py                    |   3 +-
 lib/portage/versions.py                            |  17 ++-
 60 files changed, 409 insertions(+), 481 deletions(-)

diff --git a/lib/_emerge/EbuildBuild.py b/lib/_emerge/EbuildBuild.py
index a575835b7..4da815988 100644
--- a/lib/_emerge/EbuildBuild.py
+++ b/lib/_emerge/EbuildBuild.py
@@ -159,18 +159,18 @@ class EbuildBuild(CompositeTask):
                                                settings=self.settings),
                                                self._default_final_exit)
                                return
-                       else:
-                               fetcher = EbuildFetcher(
-                                       config_pool=self.config_pool,
-                                       ebuild_path=self._ebuild_path,
-                                       fetchall=self.opts.fetch_all_uri,
-                                       fetchonly=self.opts.fetchonly,
-                                       background=False,
-                                       logfile=None,
-                                       pkg=self.pkg,
-                                       scheduler=self.scheduler)
-                               self._start_task(fetcher, self._fetchonly_exit)
-                               return
+
+                       fetcher = EbuildFetcher(
+                               config_pool=self.config_pool,
+                               ebuild_path=self._ebuild_path,
+                               fetchall=self.opts.fetch_all_uri,
+                               fetchonly=self.opts.fetchonly,
+                               background=False,
+                               logfile=None,
+                               pkg=self.pkg,
+                               scheduler=self.scheduler)
+                       self._start_task(fetcher, self._fetchonly_exit)
+                       return
 
                self._build_dir = EbuildBuildDir(
                        scheduler=self.scheduler, settings=settings)

diff --git a/lib/_emerge/MergeListItem.py b/lib/_emerge/MergeListItem.py
index 938f8014a..3b65b16a2 100644
--- a/lib/_emerge/MergeListItem.py
+++ b/lib/_emerge/MergeListItem.py
@@ -85,7 +85,7 @@ class MergeListItem(CompositeTask):
                        self._start_task(build, self._default_final_exit)
                        return
 
-               elif pkg.type_name == "binary":
+               if pkg.type_name == "binary":
 
                        binpkg = Binpkg(background=self.background,
                                find_blockers=find_blockers,

diff --git a/lib/_emerge/Package.py b/lib/_emerge/Package.py
index bf75fd97f..00d250125 100644
--- a/lib/_emerge/Package.py
+++ b/lib/_emerge/Package.py
@@ -724,7 +724,8 @@ class Package(Task):
                        """
                        if flag in self.all:
                                return flag
-                       elif flag in self.all_aliases:
+
+                       if flag in self.all_aliases:
                                for k, v in self.alias_mapping.items():
                                        if flag in v:
                                                return k

diff --git a/lib/_emerge/actions.py b/lib/_emerge/actions.py
index 2cbca99d8..ab614d641 100644
--- a/lib/_emerge/actions.py
+++ b/lib/_emerge/actions.py
@@ -1072,10 +1072,9 @@ def _calc_depclean(settings, trees, ldpath_mtimes,
                """Sort Package instances by cpv."""
                if pkg1.cpv > pkg2.cpv:
                        return 1
-               elif pkg1.cpv == pkg2.cpv:
+               if pkg1.cpv == pkg2.cpv:
                        return 0
-               else:
-                       return -1
+               return -1
 
        def create_cleanlist():
 
@@ -2984,7 +2983,7 @@ def run_action(emerge_config):
                        emerge_config.target_config.trees['vartree'].dbapi) + 
'\n',
                        noiselevel=-1)
                return 0
-       elif emerge_config.action == 'help':
+       if emerge_config.action == 'help':
                emerge_help()
                return 0
 
@@ -3018,7 +3017,7 @@ def run_action(emerge_config):
                writemsg_stdout("".join("%s\n" % s for s in
                        sorted(emerge_config.target_config.sets)))
                return os.EX_OK
-       elif emerge_config.action == "check-news":
+       if emerge_config.action == "check-news":
                news_counts = count_unread_news(
                        emerge_config.target_config.trees["porttree"].dbapi,
                        emerge_config.target_config.trees["vartree"].dbapi)
@@ -3241,7 +3240,7 @@ def run_action(emerge_config):
 
        if "sync" == emerge_config.action:
                return action_sync(emerge_config)
-       elif "metadata" == emerge_config.action:
+       if "metadata" == emerge_config.action:
                action_metadata(emerge_config.target_config.settings,
                        emerge_config.target_config.trees['porttree'].dbapi,
                        emerge_config.opts)

diff --git a/lib/_emerge/depgraph.py b/lib/_emerge/depgraph.py
index 3ff90190d..04b824ab9 100644
--- a/lib/_emerge/depgraph.py
+++ b/lib/_emerge/depgraph.py
@@ -262,7 +262,7 @@ class _rebuild_config:
                        if self._needs_rebuild(dep_pkg):
                                self.rebuild_list.add(root_slot)
                                return True
-                       elif ("--usepkg" in self._frozen_config.myopts and
+                       if ("--usepkg" in self._frozen_config.myopts and
                                (dep_root_slot in self.reinstall_list or
                                dep_root_slot in self.rebuild_list or
                                not dep_pkg.installed)):
@@ -296,7 +296,7 @@ class _rebuild_config:
                                        #    built without dep_pkg. Force 
rebuild.
                                        self.rebuild_list.add(root_slot)
                                        return True
-                               elif (parent.installed and
+                               if (parent.installed and
                                        root_slot not in self.reinstall_list):
                                        try:
                                                bin_build_time, = 
bindb.aux_get(parent.cpv,
@@ -2566,14 +2566,14 @@ class depgraph:
                        Atom("=%s" % inst_pkg.cpv)):
                        if not pkg.built:
                                return pkg.slot_atom
-                       elif not pkg.installed:
+                       if not pkg.installed:
                                # avoid using SLOT from a built instance
                                built_pkgs.append(pkg)
 
                for pkg in self._iter_similar_available(inst_pkg, 
inst_pkg.slot_atom):
                        if not pkg.built:
                                return pkg.slot_atom
-                       elif not pkg.installed:
+                       if not pkg.installed:
                                # avoid using SLOT from a built instance
                                built_pkgs.append(pkg)
 
@@ -2899,58 +2899,58 @@ class depgraph:
                                        
self._slot_operator_unsatisfied_probe(dep)):
                                        
self._slot_operator_unsatisfied_backtrack(dep)
                                        return 1
-                               else:
-                                       # This is for backward-compatibility 
with previous
-                                       # behavior, so that installed packages 
with unsatisfied
-                                       # dependencies trigger an error message 
but do not
-                                       # cause the dependency calculation to 
fail. Only do
-                                       # this if the parent is already in the 
runtime package
-                                       # mask, since otherwise we need to 
backtrack.
-                                       if (dep.parent.installed and
-                                               dep.parent in 
self._dynamic_config._runtime_pkg_mask and
-                                               not 
any(self._iter_match_pkgs_any(
-                                               dep.parent.root_config, 
dep.atom))):
-                                               
self._dynamic_config._initially_unsatisfied_deps.append(dep)
-                                               return 1
-
-                                       # Do not backtrack if only USE have to 
be changed in
-                                       # order to satisfy the dependency. Note 
that when
-                                       # want_restart_for_use_change sets the 
need_restart
-                                       # flag, it causes 
_select_pkg_highest_available to
-                                       # return None, and eventually we come 
through here
-                                       # and skip the "missing dependency" 
backtracking path.
-                                       dep_pkg, existing_node = \
-                                               self._select_package(dep.root,
-                                                       dep.atom.without_use if 
dep.atom.package
-                                                       else dep.atom, 
onlydeps=dep.onlydeps)
-                                       if dep_pkg is None:
-
-                                               # In order to suppress the sort 
of aggressive
-                                               # backtracking that can trigger 
undesirable downgrades
-                                               # as in bug 693836, do not 
backtrack if there's an
-                                               # available package which was 
involved in a slot
-                                               # conflict and satisfied all 
involved parent atoms.
-                                               for dep_pkg, reasons in 
self._dynamic_config._runtime_pkg_mask.items():
-                                                       if 
(dep.atom.match(dep_pkg) and
-                                                               len(reasons) == 
1 and
-                                                               not 
reasons.get("slot conflict", True)):
-                                                               
self._dynamic_config._skip_restart = True
-                                                               return 0
 
-                                               
self._dynamic_config._backtrack_infos["missing dependency"] = dep
-                                               
self._dynamic_config._need_restart = True
-                                               if debug:
-                                                       msg = []
-                                                       msg.append("")
-                                                       msg.append("")
-                                                       
msg.append("backtracking due to unsatisfied dep:")
-                                                       msg.append("    parent: 
%s" % dep.parent)
-                                                       msg.append("  priority: 
%s" % dep.priority)
-                                                       msg.append("      root: 
%s" % dep.root)
-                                                       msg.append("      atom: 
%s" % dep.atom)
-                                                       msg.append("")
-                                                       
writemsg_level("".join("%s\n" % l for l in msg),
-                                                               noiselevel=-1, 
level=logging.DEBUG)
+                               # This is for backward-compatibility with 
previous
+                               # behavior, so that installed packages with 
unsatisfied
+                               # dependencies trigger an error message but do 
not
+                               # cause the dependency calculation to fail. 
Only do
+                               # this if the parent is already in the runtime 
package
+                               # mask, since otherwise we need to backtrack.
+                               if (dep.parent.installed and
+                                       dep.parent in 
self._dynamic_config._runtime_pkg_mask and
+                                       not any(self._iter_match_pkgs_any(
+                                       dep.parent.root_config, dep.atom))):
+                                       
self._dynamic_config._initially_unsatisfied_deps.append(dep)
+                                       return 1
+
+                               # Do not backtrack if only USE have to be 
changed in
+                               # order to satisfy the dependency. Note that 
when
+                               # want_restart_for_use_change sets the 
need_restart
+                               # flag, it causes _select_pkg_highest_available 
to
+                               # return None, and eventually we come through 
here
+                               # and skip the "missing dependency" 
backtracking path.
+                               dep_pkg, existing_node = \
+                                       self._select_package(dep.root,
+                                               dep.atom.without_use if 
dep.atom.package
+                                               else dep.atom, 
onlydeps=dep.onlydeps)
+                               if dep_pkg is None:
+
+                                       # In order to suppress the sort of 
aggressive
+                                       # backtracking that can trigger 
undesirable downgrades
+                                       # as in bug 693836, do not backtrack if 
there's an
+                                       # available package which was involved 
in a slot
+                                       # conflict and satisfied all involved 
parent atoms.
+                                       for dep_pkg, reasons in 
self._dynamic_config._runtime_pkg_mask.items():
+                                               if (dep.atom.match(dep_pkg) and
+                                                       len(reasons) == 1 and
+                                                       not reasons.get("slot 
conflict", True)):
+                                                       
self._dynamic_config._skip_restart = True
+                                                       return 0
+
+                                       
self._dynamic_config._backtrack_infos["missing dependency"] = dep
+                                       self._dynamic_config._need_restart = 
True
+                                       if debug:
+                                               msg = []
+                                               msg.append("")
+                                               msg.append("")
+                                               msg.append("backtracking due to 
unsatisfied dep:")
+                                               msg.append("    parent: %s" % 
dep.parent)
+                                               msg.append("  priority: %s" % 
dep.priority)
+                                               msg.append("      root: %s" % 
dep.root)
+                                               msg.append("      atom: %s" % 
dep.atom)
+                                               msg.append("")
+                                               writemsg_level("".join("%s\n" % 
l for l in msg),
+                                                       noiselevel=-1, 
level=logging.DEBUG)
 
                        return 0
 
@@ -3190,7 +3190,7 @@ class depgraph:
                dep_stack = self._dynamic_config._dep_stack
                if "recurse" not in self._dynamic_config.myparams:
                        return 1
-               elif pkg.installed and not recurse:
+               if pkg.installed and not recurse:
                        dep_stack = self._dynamic_config._ignored_deps
 
                self._spinner_update()
@@ -5656,9 +5656,8 @@ class depgraph:
                if atom.package:
                        return self._iter_match_pkgs_atom(root_config, pkg_type,
                                atom, onlydeps=onlydeps)
-               else:
-                       return self._iter_match_pkgs_soname(root_config, 
pkg_type,
-                               atom, onlydeps=onlydeps)
+               return self._iter_match_pkgs_soname(root_config, pkg_type,
+                       atom, onlydeps=onlydeps)
 
        def _iter_match_pkgs_soname(self, root_config, pkg_type, atom,
                onlydeps=False):
@@ -5873,12 +5872,11 @@ class depgraph:
                deep = self._dynamic_config.myparams.get("deep", 0)
                if depth is self._UNREACHABLE_DEPTH:
                        return True
-               elif deep is True:
+               if deep is True:
                        return False
-               else:
-                       # All non-integer cases are handled above,
-                       # so both values must be int type.
-                       return depth > deep
+               # All non-integer cases are handled above,
+               # so both values must be int type.
+               return depth > deep
 
        def _depth_increment(self, depth, n=1):
                """
@@ -6161,8 +6159,7 @@ class depgraph:
                if target_use is None:
                        if needed_use_config_change is None:
                                return pkg.use.enabled
-                       else:
-                               return needed_use_config_change[0]
+                       return needed_use_config_change[0]
 
                if needed_use_config_change is not None:
                        old_use = needed_use_config_change[0]
@@ -9747,7 +9744,7 @@ class _dep_check_composite_db(dbapi):
                        if not avoid_update:
                                if not use_ebuild_visibility and usepkgonly:
                                        return False
-                               elif not 
self._depgraph._equiv_ebuild_visible(pkg):
+                               if not 
self._depgraph._equiv_ebuild_visible(pkg):
                                        return False
 
                if pkg.cp.startswith("virtual/"):

diff --git a/lib/_emerge/main.py b/lib/_emerge/main.py
index 8228e0b41..12323b17e 100644
--- a/lib/_emerge/main.py
+++ b/lib/_emerge/main.py
@@ -1239,10 +1239,10 @@ def emerge_main(args=None):
        if myaction == "help":
                emerge_help()
                return os.EX_OK
-       elif myaction == "moo":
+       if myaction == "moo":
                print(COWSAY_MOO % platform.system())
                return os.EX_OK
-       elif myaction == "sync":
+       if myaction == "sync":
                # need to set this to True now in order for the repository 
config
                # loading to allow new repos with non-existent directories
                portage._sync_mode = True

diff --git a/lib/_emerge/resolver/backtracking.py 
b/lib/_emerge/resolver/backtracking.py
index 370b6b851..bc3fb3206 100644
--- a/lib/_emerge/resolver/backtracking.py
+++ b/lib/_emerge/resolver/backtracking.py
@@ -119,8 +119,7 @@ class Backtracker:
                        node = self._unexplored_nodes.pop()
                        self._current_node = node
                        return copy.deepcopy(node.parameter)
-               else:
-                       return None
+               return None
 
 
        def __len__(self):

diff --git a/lib/_emerge/resolver/output.py b/lib/_emerge/resolver/output.py
index b4faafd75..9483898de 100644
--- a/lib/_emerge/resolver/output.py
+++ b/lib/_emerge/resolver/output.py
@@ -260,26 +260,24 @@ class Display:
                        if pkg_info.built:
                                if pkg_info.system:
                                        return 
colorize("PKG_BINARY_MERGE_SYSTEM", pkg_str)
-                               elif pkg_info.world:
+                               if pkg_info.world:
                                        return 
colorize("PKG_BINARY_MERGE_WORLD", pkg_str)
-                               else:
-                                       return colorize("PKG_BINARY_MERGE", 
pkg_str)
-                       else:
-                               if pkg_info.system:
-                                       return colorize("PKG_MERGE_SYSTEM", 
pkg_str)
-                               elif pkg_info.world:
-                                       return colorize("PKG_MERGE_WORLD", 
pkg_str)
-                               else:
-                                       return colorize("PKG_MERGE", pkg_str)
-               elif pkg_info.operation == "uninstall":
-                       return colorize("PKG_UNINSTALL", pkg_str)
-               else:
+                               return colorize("PKG_BINARY_MERGE", pkg_str)
+
                        if pkg_info.system:
-                               return colorize("PKG_NOMERGE_SYSTEM", pkg_str)
-                       elif pkg_info.world:
-                               return colorize("PKG_NOMERGE_WORLD", pkg_str)
-                       else:
-                               return colorize("PKG_NOMERGE", pkg_str)
+                               return colorize("PKG_MERGE_SYSTEM", pkg_str)
+                       if pkg_info.world:
+                               return colorize("PKG_MERGE_WORLD", pkg_str)
+                       return colorize("PKG_MERGE", pkg_str)
+
+               if pkg_info.operation == "uninstall":
+                       return colorize("PKG_UNINSTALL", pkg_str)
+
+               if pkg_info.system:
+                       return colorize("PKG_NOMERGE_SYSTEM", pkg_str)
+               if pkg_info.world:
+                       return colorize("PKG_NOMERGE_WORLD", pkg_str)
+               return colorize("PKG_NOMERGE", pkg_str)
 
 
        def verbose_size(self, pkg, repoadd_set, pkg_info):

diff --git a/lib/_emerge/resolver/slot_collision.py 
b/lib/_emerge/resolver/slot_collision.py
index 05f4256ad..cc16287de 100644
--- a/lib/_emerge/resolver/slot_collision.py
+++ b/lib/_emerge/resolver/slot_collision.py
@@ -1065,8 +1065,7 @@ class slot_conflict_handler:
 
                if is_valid_solution and required_changes:
                        return required_changes
-               else:
-                       return None
+               return None
 
 class _configuration_generator:
        def __init__(self, conflict_pkgs):
@@ -1109,13 +1108,12 @@ class _configuration_generator:
                if solution_ids[id] == len(conflict_pkgs[id])-1:
                        if id > 0:
                                return self._next(id=id-1)
-                       else:
-                               return False
-               else:
-                       solution_ids[id] += 1
-                       for other_id in range(id+1, len(solution_ids)):
-                               solution_ids[other_id] = 0
-                       return True
+                       return False
+
+               solution_ids[id] += 1
+               for other_id in range(id+1, len(solution_ids)):
+                       solution_ids[other_id] = 0
+               return True
 
 class _solution_candidate_generator:
        class _value_helper:
@@ -1124,8 +1122,7 @@ class _solution_candidate_generator:
                def __eq__(self, other):
                        if isinstance(other, str):
                                return self.value == other
-                       else:
-                               return self.value == other.value
+                       return self.value == other.value
                def __str__(self):
                        return "%s" % (self.value,)
 
@@ -1172,12 +1169,11 @@ class _solution_candidate_generator:
                if values[id].value == "enabled":
                        if id > 0:
                                return self._next(id=id-1)
-                       else:
-                               return False
-               else:
-                       values[id].value = "enabled"
-                       for other_id in range(id+1, len(values)):
-                               values[other_id].value = "disabled"
-                       return True
+                       return False
+
+               values[id].value = "enabled"
+               for other_id in range(id+1, len(values)):
+                       values[other_id].value = "disabled"
+               return True
                
                

diff --git a/lib/_emerge/unmerge.py b/lib/_emerge/unmerge.py
index 9c012e431..8de35a6ef 100644
--- a/lib/_emerge/unmerge.py
+++ b/lib/_emerge/unmerge.py
@@ -98,8 +98,8 @@ def _unmerge_display(root_config, myopts, unmerge_action,
                                                " can only be used with 
specific package names")
                                print()
                                return 1, {}
-                       else:
-                               global_unmerge = 1
+
+                       global_unmerge = 1
 
                localtree = vartree
                # process all arguments and add all

diff --git a/lib/portage/_emirrordist/FetchTask.py 
b/lib/portage/_emirrordist/FetchTask.py
index f2cf2aa20..f2342362d 100644
--- a/lib/portage/_emirrordist/FetchTask.py
+++ b/lib/portage/_emirrordist/FetchTask.py
@@ -230,12 +230,11 @@ class FetchTask(CompositeTask):
                if self._fs_mirror_stack:
                        self._fetch_fs(self._fs_mirror_stack.pop())
                        return
-               else:
-                       uri = self._next_uri()
-                       if uri is not None:
-                               self._tried_uris.add(uri)
-                               self._fetch_uri(uri)
-                               return
+               uri = self._next_uri()
+               if uri is not None:
+                       self._tried_uris.add(uri)
+                       self._fetch_uri(uri)
+                       return
 
                if self._tried_uris:
                        msg = "all uris failed"
@@ -350,14 +349,14 @@ class FetchTask(CompositeTask):
                                        self.returncode = os.EX_OK
                                        self.wait()
                                        return
-                               else:
-                                       self._start_task(
-                                               FileCopier(src_path=src, 
dest_path=dest,
-                                                       
background=(self.background and
-                                                               self._log_path 
is not None),
-                                                       logfile=self._log_path),
-                                               self._fs_mirror_copier_exit)
-                                       return
+
+                               self._start_task(
+                                       FileCopier(src_path=src, dest_path=dest,
+                                               background=(self.background and
+                                                       self._log_path is not 
None),
+                                               logfile=self._log_path),
+                                       self._fs_mirror_copier_exit)
+                               return
 
                self._try_next_mirror()
 
@@ -598,11 +597,10 @@ class FetchTask(CompositeTask):
        def _select_hash(self):
                if default_hash_name in self.digests:
                        return default_hash_name
-               else:
-                       for hash_name in self.digests:
-                               if hash_name != "size" and \
-                                       hash_name in 
portage.checksum.get_valid_checksum_keys():
-                                       return hash_name
+               for hash_name in self.digests:
+                       if hash_name != "size" and \
+                               hash_name in 
portage.checksum.get_valid_checksum_keys():
+                               return hash_name
 
                return None
 

diff --git a/lib/portage/_global_updates.py b/lib/portage/_global_updates.py
index 6a595da56..730ade592 100644
--- a/lib/portage/_global_updates.py
+++ b/lib/portage/_global_updates.py
@@ -149,8 +149,7 @@ def _do_global_updates(trees, prev_mtimes, quiet=False, 
if_mtime_changed=True):
                                if portdb.match(atoma):
                                        world_warnings.add((atoma, atomb))
                                return True
-                       else:
-                               return False
+                       return False
 
                for update_cmd in myupd:
                        for pos, atom in enumerate(world_list):

diff --git a/lib/portage/_legacy_globals.py b/lib/portage/_legacy_globals.py
index 45113d150..a9f8aa62d 100644
--- a/lib/portage/_legacy_globals.py
+++ b/lib/portage/_legacy_globals.py
@@ -15,7 +15,7 @@ def _get_legacy_global(name):
                constructed.add(name)
                return getattr(portage, name)
 
-       elif name in ('mtimedb', 'mtimedbfile'):
+       if name in ('mtimedb', 'mtimedbfile'):
                portage.mtimedbfile = os.path.join(portage.settings['EROOT'],
                        CACHE_PATH, "mtimedb")
                constructed.add('mtimedbfile')

diff --git a/lib/portage/_sets/__init__.py b/lib/portage/_sets/__init__.py
index 38490d7cc..6c6df4cca 100644
--- a/lib/portage/_sets/__init__.py
+++ b/lib/portage/_sets/__init__.py
@@ -29,12 +29,11 @@ SETPREFIX = "@"
 def get_boolean(options, name, default):
        if not name in options:
                return default
-       elif options[name].lower() in ("1", "yes", "on", "true"):
+       if options[name].lower() in ("1", "yes", "on", "true"):
                return True
-       elif options[name].lower() in ("0", "no", "off", "false"):
+       if options[name].lower() in ("0", "no", "off", "false"):
                return False
-       else:
-               raise SetConfigError(_("invalid value '%(value)s' for option 
'%(option)s'") % {"value": options[name], "option": name})
+       raise SetConfigError(_("invalid value '%(value)s' for option 
'%(option)s'") % {"value": options[name], "option": name})
 
 class SetConfigError(Exception):
        pass

diff --git a/lib/portage/_sets/base.py b/lib/portage/_sets/base.py
index 46446ccad..06e0a3cd4 100644
--- a/lib/portage/_sets/base.py
+++ b/lib/portage/_sets/base.py
@@ -100,8 +100,7 @@ class PackageSet:
        def getMetadata(self, key):
                if hasattr(self, key.lower()):
                        return getattr(self, key.lower())
-               else:
-                       return ""
+               return ""
        
        def _updateAtomMap(self, atoms=None):
                """Update self._atommap for specific atoms or all atoms."""

diff --git a/lib/portage/_sets/dbapi.py b/lib/portage/_sets/dbapi.py
index 98935f39e..a9e1b6880 100644
--- a/lib/portage/_sets/dbapi.py
+++ b/lib/portage/_sets/dbapi.py
@@ -358,8 +358,7 @@ class AgeSet(EverythingSet):
                if ((self._mode == "older" and age <= self._age) \
                        or (self._mode == "newer" and age >= self._age)):
                        return False
-               else:
-                       return True
+               return True
        
        def singleBuilder(cls, options, settings, trees):
                mode = options.get("mode", "older")
@@ -394,8 +393,7 @@ class DateSet(EverythingSet):
                if ((self._mode == "older" and date < self._date) \
                        or (self._mode == "newer" and date > self._date)):
                        return True
-               else:
-                       return False
+               return False
 
        def singleBuilder(cls, options, settings, trees):
                vardbapi = trees["vartree"].dbapi
@@ -508,25 +506,24 @@ class ChangedDepsSet(PackageSet):
                                if isinstance(depatom, list):
                                        # process the nested list.
                                        return [clean_subslots(x, usel) for x 
in depatom]
-                               else:
-                                       try:
-                                               # this can be either an atom or 
some special operator.
-                                               # in the latter case, we get 
InvalidAtom and pass it as-is.
-                                               a = Atom(depatom)
-                                       except InvalidAtom:
-                                               return depatom
-                                       else:
-                                               # if we're processing portdb, 
we need to evaluate USE flag
-                                               # dependency conditionals to 
make them match vdb. this
-                                               # requires passing the list of 
USE flags, so we reuse it
-                                               # as conditional for the 
operation as well.
-                                               if usel is not None:
-                                                       a = 
a.evaluate_conditionals(usel)
-
-                                               # replace slot operator := 
dependencies with plain :=
-                                               # since we can't properly 
compare expanded slots
-                                               # in vardb to abstract slots in 
portdb.
-                                               return 
subslot_repl_re.sub(':=', a)
+
+                               try:
+                                       # this can be either an atom or some 
special operator.
+                                       # in the latter case, we get 
InvalidAtom and pass it as-is.
+                                       a = Atom(depatom)
+                               except InvalidAtom:
+                                       return depatom
+                               # if we're processing portdb, we need to 
evaluate USE flag
+                               # dependency conditionals to make them match 
vdb. this
+                               # requires passing the list of USE flags, so we 
reuse it
+                               # as conditional for the operation as well.
+                               if usel is not None:
+                                       a = a.evaluate_conditionals(usel)
+
+                               # replace slot operator := dependencies with 
plain :=
+                               # since we can't properly compare expanded slots
+                               # in vardb to abstract slots in portdb.
+                               return subslot_repl_re.sub(':=', a)
 
                        # get all *DEPEND variables from vdb & portdb and 
compare them.
                        # we need to do some cleaning up & expansion to make 
matching

diff --git a/lib/portage/cache/ebuild_xattr.py 
b/lib/portage/cache/ebuild_xattr.py
index 27e34c3f7..6b42d79df 100644
--- a/lib/portage/cache/ebuild_xattr.py
+++ b/lib/portage/cache/ebuild_xattr.py
@@ -90,8 +90,7 @@ class database(fs_template.FsBased):
                except IOError as e:
                        if not default is None and errno.ENODATA == e.errno:
                                return default
-                       else:
-                               raise NoValueException()
+                       raise NoValueException()
 
        def __remove(self,path,key):
                xattr.remove(path,key,namespace=self.ns)

diff --git a/lib/portage/cache/mappings.py b/lib/portage/cache/mappings.py
index 3c1a0a366..5933981b9 100644
--- a/lib/portage/cache/mappings.py
+++ b/lib/portage/cache/mappings.py
@@ -242,7 +242,7 @@ class LazyLoad(Mapping):
        def __getitem__(self, key):
                if key in self.d:
                        return self.d[key]
-               elif self.pull != None:
+               if self.pull != None:
                        self.d.update(self.pull())
                        self.pull = None
                return self.d[key]
@@ -256,7 +256,7 @@ class LazyLoad(Mapping):
        def __contains__(self, key):
                if key in self.d:
                        return True
-               elif self.pull != None:
+               if self.pull != None:
                        self.d.update(self.pull())
                        self.pull = None
                return key in self.d

diff --git a/lib/portage/cache/sqlite.py b/lib/portage/cache/sqlite.py
index 647fd4dae..02bf3fcde 100644
--- a/lib/portage/cache/sqlite.py
+++ b/lib/portage/cache/sqlite.py
@@ -263,10 +263,9 @@ class database(fs_template.FsBased):
                result = cursor.fetchall()
                if len(result) == 0:
                        return False
-               elif len(result) == 1:
+               if len(result) == 1:
                        return True
-               else:
-                       raise cache_errors.CacheCorruption(cpv, "key is not 
unique")
+               raise cache_errors.CacheCorruption(cpv, "key is not unique")
 
        def __iter__(self):
                """generator for walking the dir struct"""

diff --git a/lib/portage/checksum.py b/lib/portage/checksum.py
index 6e92b17b9..8f01f6ac4 100644
--- a/lib/portage/checksum.py
+++ b/lib/portage/checksum.py
@@ -382,7 +382,7 @@ class _hash_filter:
                for token in self._tokens:
                        if token in matches:
                                return True
-                       elif token[:1] == "-":
+                       if token[:1] == "-":
                                if token[1:] in matches:
                                        return False
                return False

diff --git a/lib/portage/cvstree.py b/lib/portage/cvstree.py
index 33501d56c..796462af2 100644
--- a/lib/portage/cvstree.py
+++ b/lib/portage/cvstree.py
@@ -29,10 +29,9 @@ def pathdata(entries, path):
                        return None
        if mytarget in myentries["dirs"]:
                return myentries["dirs"][mytarget]
-       elif mytarget in myentries["files"]:
+       if mytarget in myentries["files"]:
                return myentries["files"][mytarget]
-       else:
-               return None
+       return None
 
 def fileat(entries, path):
        return pathdata(entries, path)

diff --git a/lib/portage/data.py b/lib/portage/data.py
index 93ddfec03..3887ad32e 100644
--- a/lib/portage/data.py
+++ b/lib/portage/data.py
@@ -185,10 +185,9 @@ def _get_global(k):
 
                if k == 'portage_gid':
                        return portage_gid
-               elif k == 'portage_uid':
+               if k == 'portage_uid':
                        return portage_uid
-               else:
-                       raise AssertionError('unknown name: %s' % k)
+               raise AssertionError('unknown name: %s' % k)
 
        elif k == 'userpriv_groups':
                v = [_get_global('portage_gid')]

diff --git a/lib/portage/dbapi/IndexedPortdb.py 
b/lib/portage/dbapi/IndexedPortdb.py
index e8c5790c2..5f1cb5bd1 100644
--- a/lib/portage/dbapi/IndexedPortdb.py
+++ b/lib/portage/dbapi/IndexedPortdb.py
@@ -159,8 +159,7 @@ class IndexedPortdb:
 
                if atom == atom.cp:
                        return cp_list[:]
-               else:
-                       return portage.match_from_list(atom, cp_list)
+               return portage.match_from_list(atom, cp_list)
 
        def aux_get(self, cpv, attrs, myrepo=None):
                if len(attrs) == 1 and attrs[0] == "DESCRIPTION":

diff --git a/lib/portage/dbapi/IndexedVardb.py 
b/lib/portage/dbapi/IndexedVardb.py
index dfa72ff9e..a04e3074c 100644
--- a/lib/portage/dbapi/IndexedVardb.py
+++ b/lib/portage/dbapi/IndexedVardb.py
@@ -97,8 +97,7 @@ class IndexedVardb:
 
                if atom == atom.cp:
                        return cp_list[:]
-               else:
-                       return portage.match_from_list(atom, cp_list)
+               return portage.match_from_list(atom, cp_list)
 
        def aux_get(self, cpv, attrs, myrepo=None):
                pkg_data = self._vardb._aux_cache["packages"].get(cpv)

diff --git a/lib/portage/dbapi/bintree.py b/lib/portage/dbapi/bintree.py
index 75c08f5a3..e86fa5caa 100644
--- a/lib/portage/dbapi/bintree.py
+++ b/lib/portage/dbapi/bintree.py
@@ -139,7 +139,7 @@ class bindbapi(fakedbapi):
                add_pkg = self.bintree._additional_pkgs.get(instance_key)
                if add_pkg is not None:
                        return add_pkg._db.aux_get(add_pkg, wants)
-               elif not self.bintree._remotepkgs or \
+               if not self.bintree._remotepkgs or \
                        not self.bintree.isremote(mycpv):
                        try:
                                tbz2_path = 
self.bintree._pkg_paths[instance_key]
@@ -154,7 +154,7 @@ class bindbapi(fakedbapi):
                        def getitem(k):
                                if k == "_mtime_":
                                        return str(st[stat.ST_MTIME])
-                               elif k == "SIZE":
+                               if k == "SIZE":
                                        return str(st.st_size)
                                v = metadata_bytes.get(_unicode_encode(k,
                                        encoding=_encodings['repo.content'],
@@ -1657,7 +1657,7 @@ class binarytree:
                instance_key = self.dbapi._instance_key(pkgname)
                if instance_key not in self._remotepkgs:
                        return False
-               elif instance_key in self._additional_pkgs:
+               if instance_key in self._additional_pkgs:
                        return False
                # Presence in self._remotepkgs implies that it's remote. When a
                # package is downloaded, state is updated by self.inject().
@@ -1682,10 +1682,10 @@ class binarytree:
                if os.path.exists(tbz2_path):
                        if tbz2name[:-5] not in self.invalids:
                                return
-                       else:
-                               resume = True
-                               writemsg(_("Resuming download of this tbz2, but 
it is possible that it is corrupt.\n"),
-                                       noiselevel=-1)
+
+                       resume = True
+                       writemsg(_("Resuming download of this tbz2, but it is 
possible that it is corrupt.\n"),
+                               noiselevel=-1)
                
                mydest = os.path.dirname(self.getname(pkgname))
                self._ensure_dir(mydest)

diff --git a/lib/portage/dbapi/cpv_expand.py b/lib/portage/dbapi/cpv_expand.py
index 88e43f24e..a1a91f554 100644
--- a/lib/portage/dbapi/cpv_expand.py
+++ b/lib/portage/dbapi/cpv_expand.py
@@ -100,7 +100,5 @@ def cpv_expand(mycpv, mydb=None, use_cache=1, 
settings=None):
        if mysplit:
                if mysplit[2]=="r0":
                        return mykey+"-"+mysplit[1]
-               else:
-                       return mykey+"-"+mysplit[1]+"-"+mysplit[2]
-       else:
-               return mykey
+               return mykey+"-"+mysplit[1]+"-"+mysplit[2]
+       return mykey

diff --git a/lib/portage/dbapi/porttree.py b/lib/portage/dbapi/porttree.py
index c00fb3059..4b714a919 100644
--- a/lib/portage/dbapi/porttree.py
+++ b/lib/portage/dbapi/porttree.py
@@ -930,8 +930,7 @@ class portdbapi(dbapi):
                        return 0
                if self.findname(cps[0] + "/" + cps2[1], myrepo=myrepo):
                        return 1
-               else:
-                       return 0
+               return 0
 
        def cp_all(self, categories=None, trees=None, reverse=False, sort=True):
                """
@@ -1497,7 +1496,7 @@ def _async_manifest_fetchlist(portdb, repo_config, cp, 
cpv_list=None,
 
                if result.cancelled():
                        return
-               elif e is None:
+               if e is None:
                        result.set_result(dict((k, list(v.result()))
                                for k, v in zip(cpv_list, 
gather_result.result())))
                else:

diff --git a/lib/portage/dbapi/vartree.py b/lib/portage/dbapi/vartree.py
index 0b04ab8ea..fcf164e82 100644
--- a/lib/portage/dbapi/vartree.py
+++ b/lib/portage/dbapi/vartree.py
@@ -1576,8 +1576,7 @@ class vartree:
                        use_cache=use_cache))
                if mymatch is None:
                        return ""
-               else:
-                       return mymatch
+               return mymatch
 
        def dep_match(self, mydep, use_cache=1):
                "compatibility method -- we want to see all matches, not just 
visible ones"
@@ -1585,8 +1584,7 @@ class vartree:
                mymatch = self.dbapi.match(mydep, use_cache=use_cache)
                if mymatch is None:
                        return []
-               else:
-                       return mymatch
+               return mymatch
 
        def exists_specific(self, cpv):
                return self.dbapi.cpv_exists(cpv)

diff --git a/lib/portage/dbapi/virtual.py b/lib/portage/dbapi/virtual.py
index 807d89bb2..f62fc2a30 100644
--- a/lib/portage/dbapi/virtual.py
+++ b/lib/portage/dbapi/virtual.py
@@ -123,8 +123,7 @@ class fakedbapi(dbapi):
        def cpv_all(self):
                if self._multi_instance:
                        return [x[0] for x in self.cpvdict]
-               else:
-                       return list(self.cpvdict)
+               return list(self.cpvdict)
 
        def cpv_inject(self, mycpv, metadata=None):
                """Adds a cpv to the list of available packages. See the

diff --git a/lib/portage/debug.py b/lib/portage/debug.py
index f7a7cabb2..4db9da53b 100644
--- a/lib/portage/debug.py
+++ b/lib/portage/debug.py
@@ -63,7 +63,7 @@ class trace_handler:
                        if len(my_repr) > self.max_repr_length:
                                my_repr = "'omitted'"
                        return "value=%s " % my_repr
-               elif "exception" == event:
+               if "exception" == event:
                        my_repr = repr(arg[1])
                        if len(my_repr) > self.max_repr_length:
                                my_repr = "'omitted'"
@@ -112,9 +112,9 @@ class prefix_trimmer:
                The previous result is automatically cached."""
                if s == self.previous:
                        return self.previous_trimmed
+
+               if s.startswith(self.prefix):
+                       self.previous_trimmed = s[self.cut_index:]
                else:
-                       if s.startswith(self.prefix):
-                               self.previous_trimmed = s[self.cut_index:]
-                       else:
-                               self.previous_trimmed = s
-                       return self.previous_trimmed
+                       self.previous_trimmed = s
+               return self.previous_trimmed

diff --git a/lib/portage/dep/__init__.py b/lib/portage/dep/__init__.py
index c088ea009..36f0dc8c9 100644
--- a/lib/portage/dep/__init__.py
+++ b/lib/portage/dep/__init__.py
@@ -71,7 +71,7 @@ def _match_slot(atom, pkg):
        if pkg.slot == atom.slot:
                if not atom.sub_slot:
                        return True
-               elif atom.sub_slot == pkg.sub_slot:
+               if atom.sub_slot == pkg.sub_slot:
                        return True
        return False
 
@@ -582,7 +582,7 @@ def _use_reduce_cached(depstr, uselist, masklist, matchall, 
excludeall, \
                                                if stack[k] and 
isinstance(stack[k][-1], str):
                                                        if stack[k][-1] == "||":
                                                                return k
-                                                       elif stack[k][-1][-1] 
!= "?":
+                                                       if stack[k][-1][-1] != 
"?":
                                                                return -1
                                                k -= 1
                                        return -1
@@ -1701,8 +1701,7 @@ class 
ExtendedAtomDict(portage.cache.mappings.MutableMapping):
        def __delitem__(self, cp):
                if "*" in cp:
                        return self._extended.__delitem__(cp)
-               else:
-                       return self._normal.__delitem__(cp)
+               return self._normal.__delitem__(cp)
 
        keys = __iter__
        items = iteritems
@@ -1713,8 +1712,7 @@ class 
ExtendedAtomDict(portage.cache.mappings.MutableMapping):
        def setdefault(self, cp, default=None):
                if "*" in cp:
                        return self._extended.setdefault(cp, default)
-               else:
-                       return self._normal.setdefault(cp, default)
+               return self._normal.setdefault(cp, default)
 
        def __getitem__(self, cp):
 
@@ -1831,8 +1829,7 @@ def dep_getslot(mydep):
                bracket = mydep.find("[", colon)
                if bracket == -1:
                        return mydep[colon+1:]
-               else:
-                       return mydep[colon+1:bracket]
+               return mydep[colon+1:bracket]
        return None
 
 def dep_getrepo(mydep):
@@ -1863,8 +1860,7 @@ def dep_getrepo(mydep):
                bracket = mydep.find("[", colon)
                if bracket == -1:
                        return mydep[colon+2:]
-               else:
-                       return mydep[colon+2:bracket]
+               return mydep[colon+2:bracket]
        return None
 
 def remove_slot(mydep):
@@ -2615,11 +2611,11 @@ def check_required_use(required_use, use, iuse_match, 
eapi=None):
 
                if operator == "||":
                        return (True in argument)
-               elif operator == "^^":
+               if operator == "^^":
                        return (argument.count(True) == 1)
-               elif operator == "??":
+               if operator == "??":
                        return (argument.count(True) <= 1)
-               elif operator[-1] == "?":
+               if operator[-1] == "?":
                        return (False not in argument)
 
        mysplit = required_use.split()

diff --git a/lib/portage/dep/_dnf.py b/lib/portage/dep/_dnf.py
index 90c662242..1b14d2b43 100644
--- a/lib/portage/dep/_dnf.py
+++ b/lib/portage/dep/_dnf.py
@@ -83,6 +83,6 @@ def contains_disjunction(dep_struct):
                        assert x, 'Normalization error, empty conjunction found 
in %s' % (dep_struct,)
                        if x[0] == '||':
                                return True
-                       elif is_disjunction and contains_disjunction(x):
+                       if is_disjunction and contains_disjunction(x):
                                return True
        return False

diff --git a/lib/portage/dep/dep_check.py b/lib/portage/dep/dep_check.py
index 7b2c804bc..625599725 100644
--- a/lib/portage/dep/dep_check.py
+++ b/lib/portage/dep/dep_check.py
@@ -283,14 +283,13 @@ def dep_eval(deplist):
                if len(deplist) == 1:
                        return 1
                return 0
-       else:
-               for x in deplist:
-                       if isinstance(x, list):
-                               if dep_eval(x)==0:
-                                       return 0
-                       elif x==0 or x==2:
+       for x in deplist:
+               if isinstance(x, list):
+                       if dep_eval(x)==0:
                                return 0
-               return 1
+               elif x==0 or x==2:
+                       return 0
+       return 1
 
 class _dep_choice(SlotObject):
        __slots__ = ('atoms', 'slot_map', 'cp_map', 'all_available',

diff --git a/lib/portage/elog/mod_mail_summary.py 
b/lib/portage/elog/mod_mail_summary.py
index a488e8096..31c9d25b0 100644
--- a/lib/portage/elog/mod_mail_summary.py
+++ b/lib/portage/elog/mod_mail_summary.py
@@ -50,7 +50,7 @@ def finalize():
 def _finalize(mysettings, items):
        if len(items) == 0:
                return
-       elif len(items) == 1:
+       if len(items) == 1:
                count = _("one package")
        else:
                count = _("multiple packages")

diff --git a/lib/portage/exception.py b/lib/portage/exception.py
index 5ef18f68a..30ab0c689 100644
--- a/lib/portage/exception.py
+++ b/lib/portage/exception.py
@@ -14,8 +14,7 @@ class PortageException(Exception):
        def __str__(self):
                if isinstance(self.value, str):
                        return self.value
-               else:
-                       return repr(self.value)
+               return repr(self.value)
 
 
 class PortageKeyError(KeyError, PortageException):

diff --git a/lib/portage/getbinpkg.py b/lib/portage/getbinpkg.py
index a15e3c3bf..54b918a65 100644
--- a/lib/portage/getbinpkg.py
+++ b/lib/portage/getbinpkg.py
@@ -434,8 +434,7 @@ def file_get_metadata(baseurl, conn=None, chunk_size=3000):
                        if not keepconnection:
                                conn.close()
                        return myid
-               else:
-                       xpak_data = data[len(data) - (xpaksize + 8):-8]
+               xpak_data = data[len(data) - (xpaksize + 8):-8]
                del data
 
                myid = portage.xpak.xsplit_mem(xpak_data)
@@ -794,10 +793,9 @@ def _cmp_cpv(d1, d2):
        cpv2 = d2["CPV"]
        if cpv1 > cpv2:
                return 1
-       elif cpv1 == cpv2:
+       if cpv1 == cpv2:
                return 0
-       else:
-               return -1
+       return -1
 
 class PackageIndex:
 

diff --git a/lib/portage/glsa.py b/lib/portage/glsa.py
index ecbcde8f4..4066d6747 100644
--- a/lib/portage/glsa.py
+++ b/lib/portage/glsa.py
@@ -293,10 +293,9 @@ def match(atom, dbapi, match_type="default"):
        """
        if atom[2] == "~":
                return revisionMatch(atom, dbapi, match_type=match_type)
-       elif match_type == "default" or not hasattr(dbapi, "xmatch"):
+       if match_type == "default" or not hasattr(dbapi, "xmatch"):
                return dbapi.match(atom)
-       else:
-               return dbapi.xmatch(match_type, atom)
+       return dbapi.xmatch(match_type, atom)
 
 def revisionMatch(revisionAtom, dbapi, match_type="default"):
        """

diff --git a/lib/portage/locks.py b/lib/portage/locks.py
index 1e3186880..a0981712e 100644
--- a/lib/portage/locks.py
+++ b/lib/portage/locks.py
@@ -215,14 +215,13 @@ def _lockfile_iteration(mypath, wantnewlockfile=False, 
unlinkfile=False,
                                        if e.errno in (errno.ENOENT, 
errno.ESTALE):
                                                os.close(myfd)
                                                return None
-                                       else:
-                                               writemsg("%s: chown('%s', -1, 
%d)\n" % \
-                                                       (e, lockfilename, 
portage_gid), noiselevel=-1)
-                                               writemsg(_("Cannot chown a 
lockfile: '%s'\n") % \
-                                                       lockfilename, 
noiselevel=-1)
-                                               writemsg(_("Group IDs of 
current user: %s\n") % \
-                                                       " ".join(str(n) for n 
in os.getgroups()),
-                                                       noiselevel=-1)
+                                       writemsg("%s: chown('%s', -1, %d)\n" % \
+                                               (e, lockfilename, portage_gid), 
noiselevel=-1)
+                                       writemsg(_("Cannot chown a lockfile: 
'%s'\n") % \
+                                               lockfilename, noiselevel=-1)
+                                       writemsg(_("Group IDs of current user: 
%s\n") % \
+                                               " ".join(str(n) for n in 
os.getgroups()),
+                                               noiselevel=-1)
                finally:
                        os.umask(old_mask)
 

diff --git a/lib/portage/manifest.py b/lib/portage/manifest.py
index 37409e5d7..79c756f04 100644
--- a/lib/portage/manifest.py
+++ b/lib/portage/manifest.py
@@ -53,12 +53,11 @@ def guessManifestFileType(filename):
                return None
        if filename.startswith("files" + os.sep):
                return "AUX"
-       elif filename.endswith(".ebuild"):
+       if filename.endswith(".ebuild"):
                return "EBUILD"
-       elif filename in ["ChangeLog", "metadata.xml"]:
+       if filename in ["ChangeLog", "metadata.xml"]:
                return "MISC"
-       else:
-               return "DIST"
+       return "DIST"
 
 def guessThinManifestFileType(filename):
        filetype = guessManifestFileType(filename)

diff --git a/lib/portage/output.py b/lib/portage/output.py
index 34005c509..4c8f8a187 100644
--- a/lib/portage/output.py
+++ b/lib/portage/output.py
@@ -334,12 +334,9 @@ def colorize(color_key, text):
        if havecolor:
                if color_key in codes:
                        return codes[color_key] + text + codes["reset"]
-               elif color_key in _styles:
+               if color_key in _styles:
                        return style_to_ansi_code(color_key) + text + 
codes["reset"]
-               else:
-                       return text
-       else:
-               return text
+       return text
 
 compat_functions_colors = [
        "bold", "white", "teal", "turquoise", "darkteal",
@@ -752,6 +749,7 @@ class TermProgressBar(ProgressBar):
                bar_space = cols - percentage_str_width - square_brackets_width 
- 1
                if self._desc:
                        bar_space -= self._desc_max_length
+
                if maxval == 0:
                        max_bar_width = bar_space-3
                        _percent = "".ljust(percentage_str_width)
@@ -776,19 +774,19 @@ class TermProgressBar(ProgressBar):
                                "[" + (bar_width * " ") + \
                                "<=>" + ((max_bar_width - bar_width) * " ") + 
"]")
                        return image
-               else:
-                       percentage = 100 * curval // maxval
-                       max_bar_width = bar_space - 1
-                       _percent = ("%d%% " % 
percentage).rjust(percentage_str_width)
-                       image = "%s%s" % (self._desc, _percent)
 
-                       if cols < min_columns:
-                               return image
-                       offset = curval / maxval
-                       bar_width = int(offset * max_bar_width)
-                       image = image + "[" + (bar_width * "=") + \
-                               ">" + ((max_bar_width - bar_width) * " ") + "]"
+               percentage = 100 * curval // maxval
+               max_bar_width = bar_space - 1
+               _percent = ("%d%% " % percentage).rjust(percentage_str_width)
+               image = "%s%s" % (self._desc, _percent)
+
+               if cols < min_columns:
                        return image
+               offset = curval / maxval
+               bar_width = int(offset * max_bar_width)
+               image = image + "[" + (bar_width * "=") + \
+                       ">" + ((max_bar_width - bar_width) * " ") + "]"
+               return image
 
 _color_map_loaded = False
 

diff --git a/lib/portage/package/ebuild/_ipc/QueryCommand.py 
b/lib/portage/package/ebuild/_ipc/QueryCommand.py
index e58909a2a..7af465234 100644
--- a/lib/portage/package/ebuild/_ipc/QueryCommand.py
+++ b/lib/portage/package/ebuild/_ipc/QueryCommand.py
@@ -82,10 +82,10 @@ class QueryCommand(IpcCommand):
                        else:
                                returncode = 1
                        return ('', warnings_str, returncode)
-               elif cmd == 'best_version':
+               if cmd == 'best_version':
                        m = best(vardb.match(atom))
                        return ('%s\n' % m, warnings_str, 0)
-               elif cmd in ('master_repositories', 'repository_path', 
'available_eclasses', 'eclass_path', 'license_path'):
+               if cmd in ('master_repositories', 'repository_path', 
'available_eclasses', 'eclass_path', 'license_path'):
                        repo = _repo_name_re.match(args[0])
                        if repo is None:
                                return ('', '%s: Invalid repository: %s\n' % 
(cmd, args[0]), 2)
@@ -96,24 +96,23 @@ class QueryCommand(IpcCommand):
 
                        if cmd == 'master_repositories':
                                return ('%s\n' % ' '.join(x.name for x in 
repo.masters), warnings_str, 0)
-                       elif cmd == 'repository_path':
+                       if cmd == 'repository_path':
                                return ('%s\n' % repo.location, warnings_str, 0)
-                       elif cmd == 'available_eclasses':
+                       if cmd == 'available_eclasses':
                                return ('%s\n' % ' 
'.join(sorted(repo.eclass_db.eclasses)), warnings_str, 0)
-                       elif cmd == 'eclass_path':
+                       if cmd == 'eclass_path':
                                try:
                                        eclass = 
repo.eclass_db.eclasses[args[1]]
                                except KeyError:
                                        return ('', warnings_str, 1)
                                return ('%s\n' % eclass.location, warnings_str, 
0)
-                       elif cmd == 'license_path':
+                       if cmd == 'license_path':
                                paths = reversed([os.path.join(x.location, 
'licenses', args[1]) for x in list(repo.masters) + [repo]])
                                for path in paths:
                                        if os.path.exists(path):
                                                return ('%s\n' % path, 
warnings_str, 0)
                                return ('', warnings_str, 1)
-               else:
-                       return ('', 'Invalid command: %s\n' % cmd, 3)
+               return ('', 'Invalid command: %s\n' % cmd, 3)
 
        def _elog(self, elog_funcname, lines):
                """

diff --git a/lib/portage/package/ebuild/_parallel_manifest/ManifestProcess.py 
b/lib/portage/package/ebuild/_parallel_manifest/ManifestProcess.py
index 44e257664..cf718a796 100644
--- a/lib/portage/package/ebuild/_parallel_manifest/ManifestProcess.py
+++ b/lib/portage/package/ebuild/_parallel_manifest/ManifestProcess.py
@@ -39,5 +39,4 @@ class ManifestProcess(ForkProcess):
                else:
                        if modified:
                                return self.MODIFIED
-                       else:
-                               return os.EX_OK
+                       return os.EX_OK

diff --git a/lib/portage/package/ebuild/config.py 
b/lib/portage/package/ebuild/config.py
index d3e7af7fb..7c5f82e0c 100644
--- a/lib/portage/package/ebuild/config.py
+++ b/lib/portage/package/ebuild/config.py
@@ -97,12 +97,10 @@ def best_from_dict(key, top_dict, key_order, 
EmptyOnError=1, FullCopy=1, AllowEm
                if x in top_dict and key in top_dict[x]:
                        if FullCopy:
                                return copy.deepcopy(top_dict[x][key])
-                       else:
-                               return top_dict[x][key]
+                       return top_dict[x][key]
        if EmptyOnError:
                return ""
-       else:
-               raise KeyError("Key not found in list; '%s'" % key)
+       raise KeyError("Key not found in list; '%s'" % key)
 
 def _lazy_iuse_regex(iuse_implicit):
        """
@@ -2634,10 +2632,10 @@ class config:
                        # portage plans to update itself.
                        if mykey == "PORTAGE_BIN_PATH":
                                return portage._bin_path
-                       elif mykey == "PORTAGE_PYM_PATH":
+                       if mykey == "PORTAGE_PYM_PATH":
                                return portage._pym_path
 
-                       elif mykey == "PORTAGE_PYTHONPATH":
+                       if mykey == "PORTAGE_PYTHONPATH":
                                value = [x for x in \
                                        self.backupenv.get("PYTHONPATH", 
"").split(":") if x]
                                need_pym_path = True
@@ -2651,7 +2649,7 @@ class config:
                                        value.insert(0, portage._pym_path)
                                return ":".join(value)
 
-                       elif mykey == "PORTAGE_GID":
+                       if mykey == "PORTAGE_GID":
                                return "%s" % portage_gid
 
                for d in self.lookuplist:
@@ -2704,9 +2702,8 @@ class config:
                v = self.get(k)
                if v is not None:
                        return v
-               else:
-                       self[k] = x
-                       return x
+               self[k] = x
+               return x
 
        def __iter__(self):
                keys = set()

diff --git a/lib/portage/package/ebuild/doebuild.py 
b/lib/portage/package/ebuild/doebuild.py
index f4bb78076..7bb942966 100644
--- a/lib/portage/package/ebuild/doebuild.py
+++ b/lib/portage/package/ebuild/doebuild.py
@@ -838,7 +838,7 @@ def doebuild(myebuild, mydo, _unused=DeprecationWarning, 
settings=None, debug=0,
                        if returnpid:
                                return _spawn_phase(mydo, mysettings,
                                        fd_pipes=fd_pipes, returnpid=returnpid)
-                       elif dbkey and dbkey is not DeprecationWarning:
+                       if dbkey and dbkey is not DeprecationWarning:
                                mysettings["dbkey"] = dbkey
                        else:
                                mysettings["dbkey"] = \
@@ -847,7 +847,7 @@ def doebuild(myebuild, mydo, _unused=DeprecationWarning, 
settings=None, debug=0,
                        return _spawn_phase(mydo, mysettings,
                                fd_pipes=fd_pipes, returnpid=returnpid)
 
-               elif mydo == "nofetch":
+               if mydo == "nofetch":
 
                        if returnpid:
                                writemsg("!!! doebuild: %s\n" %
@@ -1127,11 +1127,11 @@ def doebuild(myebuild, mydo, 
_unused=DeprecationWarning, settings=None, debug=0,
                                mf = None
                                _doebuild_manifest_cache = None
                                return not digestgen(mysettings=mysettings, 
myportdb=mydbapi)
-                       elif mydo == "digest":
+                       if mydo == "digest":
                                mf = None
                                _doebuild_manifest_cache = None
                                return not digestgen(mysettings=mysettings, 
myportdb=mydbapi)
-                       elif "digest" in mysettings.features:
+                       if "digest" in mysettings.features:
                                mf = None
                                _doebuild_manifest_cache = None
                                digestgen(mysettings=mysettings, 
myportdb=mydbapi)

diff --git a/lib/portage/package/ebuild/fetch.py 
b/lib/portage/package/ebuild/fetch.py
index bcec7c97b..65cf6e123 100644
--- a/lib/portage/package/ebuild/fetch.py
+++ b/lib/portage/package/ebuild/fetch.py
@@ -453,11 +453,10 @@ class MirrorLayoutConfig:
                        if self.validate_structure(val):
                                if val[0] == 'flat':
                                        return FlatLayout(*val[1:])
-                               elif val[0] == 'filename-hash':
+                               if val[0] == 'filename-hash':
                                        return FilenameHashLayout(*val[1:])
-               else:
-                       # fallback
-                       return FlatLayout()
+               # fallback
+               return FlatLayout()
 
        def get_all_layouts(self):
                ret = []
@@ -1249,8 +1248,7 @@ def fetch(myuris, mysettings, listonly=0, fetchonly=0,
                                                        writemsg(_("!!! File %s 
is incorrect size, "
                                                                "but unable to 
retry.\n") % myfile, noiselevel=-1)
                                                return 0
-                                       else:
-                                               continue
+                                       continue
 
                                if fetched != 2 and has_space:
                                        #we either need to resume or start the 
download

diff --git a/lib/portage/package/ebuild/getmaskingreason.py 
b/lib/portage/package/ebuild/getmaskingreason.py
index 1e4ed21ce..22232de29 100644
--- a/lib/portage/package/ebuild/getmaskingreason.py
+++ b/lib/portage/package/ebuild/getmaskingreason.py
@@ -54,8 +54,7 @@ def getmaskingreason(mycpv, metadata=None, settings=None,
                # contain essential things like SLOT.
                if return_location:
                        return (None, None)
-               else:
-                       return None
+               return None
 
        # Sometimes we can't access SLOT or repository due to corruption.
        pkg = mycpv
@@ -114,13 +113,11 @@ def getmaskingreason(mycpv, metadata=None, settings=None,
                                                                comment = ""
                                                        if return_location:
                                                                return 
(comment, pmask_filename)
-                                                       else:
-                                                               return comment
+                                                       return comment
                                                elif comment_valid != -1:
                                                        # Apparently this 
comment applies to multiple masks, so
                                                        # it remains valid 
until a blank line is encountered.
                                                        comment_valid += 1
        if return_location:
                return (None, None)
-       else:
-               return None
+       return None

diff --git a/lib/portage/package/ebuild/getmaskingstatus.py 
b/lib/portage/package/ebuild/getmaskingstatus.py
index 5336a406a..cf2b7344b 100644
--- a/lib/portage/package/ebuild/getmaskingstatus.py
+++ b/lib/portage/package/ebuild/getmaskingstatus.py
@@ -85,7 +85,7 @@ def _getmaskingstatus(mycpv, settings, portdb, myrepo=None):
        restrict = metadata["RESTRICT"]
        if not eapi_is_supported(eapi):
                return [_MaskReason("EAPI", "EAPI %s" % eapi)]
-       elif _eapi_is_deprecated(eapi) and not installed:
+       if _eapi_is_deprecated(eapi) and not installed:
                return [_MaskReason("EAPI", "EAPI %s" % eapi)]
        egroups = settings.configdict["backupenv"].get(
                "ACCEPT_KEYWORDS", "").split()

diff --git a/lib/portage/repository/config.py b/lib/portage/repository/config.py
index d8ca29a9f..0f3e582f8 100644
--- a/lib/portage/repository/config.py
+++ b/lib/portage/repository/config.py
@@ -968,8 +968,7 @@ class RepoConfigLoader:
                main_repo = self.prepos['DEFAULT'].main_repo
                if main_repo is not None and main_repo in self.prepos:
                        return self.prepos[main_repo].location
-               else:
-                       return ''
+               return ''
 
        def mainRepo(self):
                """Returns the main repo"""

diff --git a/lib/portage/sync/controller.py b/lib/portage/sync/controller.py
index 32a6429a0..6b47ae953 100644
--- a/lib/portage/sync/controller.py
+++ b/lib/portage/sync/controller.py
@@ -115,8 +115,7 @@ class SyncManager:
                                "has been renamed to sync_async",
                                DeprecationWarning, stacklevel=2)
                        return self.sync_async
-               else:
-                       raise AttributeError(name)
+               raise AttributeError(name)
 
        def get_module_descriptions(self, mod):
                desc = self.module_controller.get_func_descriptions(mod)

diff --git a/lib/portage/sync/modules/git/git.py 
b/lib/portage/sync/modules/git/git.py
index ed8c1979f..d87f1a601 100644
--- a/lib/portage/sync/modules/git/git.py
+++ b/lib/portage/sync/modules/git/git.py
@@ -247,26 +247,25 @@ class GitSync(NewBase):
                        if status == 'G':  # good signature is good
                                out.einfo('Trusted signature found on top 
commit')
                                return True
-                       elif status == 'U':  # untrusted
+                       if status == 'U':  # untrusted
                                out.ewarn('Top commit signature is valid but 
not trusted')
                                return True
+                       if status == 'B':
+                               expl = 'bad signature'
+                       elif status == 'X':
+                               expl = 'expired signature'
+                       elif status == 'Y':
+                               expl = 'expired key'
+                       elif status == 'R':
+                               expl = 'revoked key'
+                       elif status == 'E':
+                               expl = 'unable to verify signature (missing 
key?)'
+                       elif status == 'N':
+                               expl = 'no signature'
                        else:
-                               if status == 'B':
-                                       expl = 'bad signature'
-                               elif status == 'X':
-                                       expl = 'expired signature'
-                               elif status == 'Y':
-                                       expl = 'expired key'
-                               elif status == 'R':
-                                       expl = 'revoked key'
-                               elif status == 'E':
-                                       expl = 'unable to verify signature 
(missing key?)'
-                               elif status == 'N':
-                                       expl = 'no signature'
-                               else:
-                                       expl = 'unknown issue'
-                               out.eerror('No valid signature found: %s' % 
(expl,))
-                               return False
+                               expl = 'unknown issue'
+                       out.eerror('No valid signature found: %s' % (expl,))
+                       return False
                finally:
                        if openpgp_env is not None:
                                openpgp_env.close()

diff --git a/lib/portage/tests/util/futures/test_retry.py 
b/lib/portage/tests/util/futures/test_retry.py
index d2605886c..ce5fb3e11 100644
--- a/lib/portage/tests/util/futures/test_retry.py
+++ b/lib/portage/tests/util/futures/test_retry.py
@@ -203,12 +203,12 @@ class RetryForkExecutorTestCase(RetryTestCase):
                                        lambda kill_switch: event.set())
                                event.wait()
                                return result.result()
-                       else:
-                               # child process
-                               try:
-                                       return 
loop.run_until_complete(coroutine_func())
-                               finally:
-                                       loop.close()
+
+                       # child process
+                       try:
+                               return loop.run_until_complete(coroutine_func())
+                       finally:
+                               loop.close()
 
                def execute_wrapper():
                        kill_switch = parent_loop.create_future()

diff --git a/lib/portage/util/__init__.py b/lib/portage/util/__init__.py
index a143bca85..84f1391f6 100644
--- a/lib/portage/util/__init__.py
+++ b/lib/portage/util/__init__.py
@@ -112,8 +112,7 @@ def normalize_path(mypath):
        if mypath.startswith(path_sep):
                # posixpath.normpath collapses 3 or more leading slashes to 
just 1.
                return os.path.normpath(2*path_sep + mypath)
-       else:
-               return os.path.normpath(mypath)
+       return os.path.normpath(mypath)
 
 def grabfile(myfilename, compat_level=0, recursive=0, 
remember_source_file=False):
        """This function grabs the lines in a file, normalizes whitespace and 
returns lines in a list; if a line
@@ -249,9 +248,9 @@ def append_repo(atom_list, repo_name, 
remember_source_file=False):
        if remember_source_file:
                return [(atom.repo is not None and atom or 
atom.with_repo(repo_name), source) \
                        for atom, source in atom_list]
-       else:
-               return [atom.repo is not None and atom or 
atom.with_repo(repo_name) \
-                       for atom in atom_list]
+
+       return [atom.repo is not None and atom or atom.with_repo(repo_name) \
+               for atom in atom_list]
 
 def stack_lists(lists, incremental=1, remember_source_file=False,
        warn_for_unmatched_removal=False, 
strict_warn_for_unmatched_removal=False, ignore_repo=False):
@@ -328,8 +327,7 @@ def stack_lists(lists, incremental=1, 
remember_source_file=False,
 
        if remember_source_file:
                return list(new_list.items())
-       else:
-               return list(new_list)
+       return list(new_list)
 
 def grabdict(myfilename, juststrings=0, empty=0, recursive=0, incremental=1, 
newlines=0):
        """
@@ -868,9 +866,8 @@ def varexpand(mystring, mydict=None, error_leader=None):
                                                                msg = 
error_leader() + msg
                                                        writemsg(msg + "\n", 
noiselevel=-1)
                                                        return ""
-                                               else:
-                                                       pos += 1
-                                                       break
+                                               pos += 1
+                                               break
                                        pos += 1
                                myvarname = mystring[myvstart:pos]
                                if braced:
@@ -880,8 +877,7 @@ def varexpand(mystring, mydict=None, error_leader=None):
                                                        msg = error_leader() + 
msg
                                                writemsg(msg + "\n", 
noiselevel=-1)
                                                return ""
-                                       else:
-                                               pos += 1
+                                       pos += 1
                                if len(myvarname) == 0:
                                        msg = "$"
                                        if braced:
@@ -1037,18 +1033,16 @@ def _do_stat(filename, follow_links=True):
        try:
                if follow_links:
                        return os.stat(filename)
-               else:
-                       return os.lstat(filename)
+               return os.lstat(filename)
        except OSError as oe:
                func_call = "stat('%s')" % filename
                if oe.errno == errno.EPERM:
                        raise OperationNotPermitted(func_call)
-               elif oe.errno == errno.EACCES:
+               if oe.errno == errno.EACCES:
                        raise PermissionDenied(func_call)
-               elif oe.errno == errno.ENOENT:
+               if oe.errno == errno.ENOENT:
                        raise FileNotFound(filename)
-               else:
-                       raise
+               raise
 
 def apply_permissions(filename, uid=-1, gid=-1, mode=-1, mask=-1,
        stat_cached=None, follow_links=True):
@@ -1480,8 +1474,7 @@ class LazyItemsDict(UserDict):
                                self[item_key] = result
                        return result
 
-               else:
-                       return UserDict.__getitem__(self, item_key)
+               return UserDict.__getitem__(self, item_key)
 
        def __setitem__(self, item_key, value):
                if item_key in self.lazy_items:

diff --git a/lib/portage/util/_async/PipeLogger.py 
b/lib/portage/util/_async/PipeLogger.py
index 39ebf9aee..060483f0b 100644
--- a/lib/portage/util/_async/PipeLogger.py
+++ b/lib/portage/util/_async/PipeLogger.py
@@ -93,51 +93,50 @@ class PipeLogger(AbstractPollTask):
                                # EOF
                                return
 
-                       else:
-                               if not background and stdout_fd is not None:
-                                       failures = 0
-                                       stdout_buf = buf
-                                       while stdout_buf:
-                                               try:
-                                                       stdout_buf = \
-                                                               
stdout_buf[os.write(stdout_fd, stdout_buf):]
-                                               except OSError as e:
-                                                       if e.errno != 
errno.EAGAIN:
-                                                               raise
-                                                       del e
-                                                       failures += 1
-                                                       if failures > 50:
-                                                               # Avoid a 
potentially infinite loop. In
-                                                               # most cases, 
the failure count is zero
-                                                               # and it's 
unlikely to exceed 1.
-                                                               raise
-
-                                                       # This means that a 
subprocess has put an inherited
-                                                       # stdio file descriptor 
(typically stdin) into
-                                                       # O_NONBLOCK mode. This 
is not acceptable (see bug
-                                                       # #264435), so revert 
it. We need to use a loop
-                                                       # here since there's a 
race condition due to
-                                                       # parallel processes 
being able to change the
-                                                       # flags on the 
inherited file descriptor.
-                                                       # TODO: When possible, 
avoid having child processes
-                                                       # inherit stdio file 
descriptors from portage
-                                                       # (maybe it can't be 
avoided with
-                                                       # 
PROPERTIES=interactive).
-                                                       fcntl.fcntl(stdout_fd, 
fcntl.F_SETFL,
-                                                               
fcntl.fcntl(stdout_fd,
-                                                               fcntl.F_GETFL) 
^ os.O_NONBLOCK)
-
-                               if log_file is not None:
-                                       if self._log_file_nb:
-                                               # Use the _writer function 
which uses os.write, since the
-                                               # log_file.write method looses 
data when an EAGAIN occurs.
-                                               yield _writer(log_file, buf, 
loop=self.scheduler)
-                                       else:
-                                               # For gzip.GzipFile instances, 
the above _writer function
-                                               # will not work because data 
written directly to the file
-                                               # descriptor bypasses 
compression.
-                                               log_file.write(buf)
-                                               log_file.flush()
+                       if not background and stdout_fd is not None:
+                               failures = 0
+                               stdout_buf = buf
+                               while stdout_buf:
+                                       try:
+                                               stdout_buf = \
+                                                       
stdout_buf[os.write(stdout_fd, stdout_buf):]
+                                       except OSError as e:
+                                               if e.errno != errno.EAGAIN:
+                                                       raise
+                                               del e
+                                               failures += 1
+                                               if failures > 50:
+                                                       # Avoid a potentially 
infinite loop. In
+                                                       # most cases, the 
failure count is zero
+                                                       # and it's unlikely to 
exceed 1.
+                                                       raise
+
+                                               # This means that a subprocess 
has put an inherited
+                                               # stdio file descriptor 
(typically stdin) into
+                                               # O_NONBLOCK mode. This is not 
acceptable (see bug
+                                               # #264435), so revert it. We 
need to use a loop
+                                               # here since there's a race 
condition due to
+                                               # parallel processes being able 
to change the
+                                               # flags on the inherited file 
descriptor.
+                                               # TODO: When possible, avoid 
having child processes
+                                               # inherit stdio file 
descriptors from portage
+                                               # (maybe it can't be avoided 
with
+                                               # PROPERTIES=interactive).
+                                               fcntl.fcntl(stdout_fd, 
fcntl.F_SETFL,
+                                                       fcntl.fcntl(stdout_fd,
+                                                       fcntl.F_GETFL) ^ 
os.O_NONBLOCK)
+
+                       if log_file is not None:
+                               if self._log_file_nb:
+                                       # Use the _writer function which uses 
os.write, since the
+                                       # log_file.write method looses data 
when an EAGAIN occurs.
+                                       yield _writer(log_file, buf, 
loop=self.scheduler)
+                               else:
+                                       # For gzip.GzipFile instances, the 
above _writer function
+                                       # will not work because data written 
directly to the file
+                                       # descriptor bypasses compression.
+                                       log_file.write(buf)
+                                       log_file.flush()
 
        def _io_loop_done(self, future):
                try:

diff --git a/lib/portage/util/_dyn_libs/LinkageMapELF.py 
b/lib/portage/util/_dyn_libs/LinkageMapELF.py
index 57fcf4682..954a956c6 100644
--- a/lib/portage/util/_dyn_libs/LinkageMapELF.py
+++ b/lib/portage/util/_dyn_libs/LinkageMapELF.py
@@ -515,24 +515,23 @@ class LinkageMapELF:
                                """
                                if obj in cache_self.cache:
                                        return cache_self.cache[obj]
-                               else:
-                                       obj_key = self._obj_key(obj)
-                                       # Check that the library exists on the 
filesystem.
-                                       if obj_key.file_exists():
-                                               # Get the arch and soname from 
LinkageMap._obj_properties if
-                                               # it exists. Otherwise, None.
-                                               obj_props = 
self._obj_properties.get(obj_key)
-                                               if obj_props is None:
-                                                       arch = None
-                                                       soname = None
-                                               else:
-                                                       arch = obj_props.arch
-                                                       soname = 
obj_props.soname
-                                               return 
cache_self.cache.setdefault(obj, \
-                                                               (arch, soname, 
obj_key, True))
+
+                               obj_key = self._obj_key(obj)
+                               # Check that the library exists on the 
filesystem.
+                               if obj_key.file_exists():
+                                       # Get the arch and soname from 
LinkageMap._obj_properties if
+                                       # it exists. Otherwise, None.
+                                       obj_props = 
self._obj_properties.get(obj_key)
+                                       if obj_props is None:
+                                               arch = None
+                                               soname = None
                                        else:
-                                               return 
cache_self.cache.setdefault(obj, \
-                                                               (None, None, 
obj_key, False))
+                                               arch = obj_props.arch
+                                               soname = obj_props.soname
+                                       return cache_self.cache.setdefault(obj, 
\
+                                                       (arch, soname, obj_key, 
True))
+                               return cache_self.cache.setdefault(obj, \
+                                               (None, None, obj_key, False))
 
                rValue = {}
                cache = _LibraryCache()

diff --git a/lib/portage/util/_urlopen.py b/lib/portage/util/_urlopen.py
index 21f59c9e2..b46d1554c 100644
--- a/lib/portage/util/_urlopen.py
+++ b/lib/portage/util/_urlopen.py
@@ -30,27 +30,27 @@ def urlopen(url, if_modified_since=None):
        parse_result = urllib_parse.urlparse(url)
        if parse_result.scheme not in ("http", "https"):
                return _urlopen(url)
-       else:
-               netloc = parse_result.netloc.rpartition('@')[-1]
-               url = urllib_parse.urlunparse((parse_result.scheme, netloc, 
parse_result.path, parse_result.params, parse_result.query, 
parse_result.fragment))
-               password_manager = 
urllib_request.HTTPPasswordMgrWithDefaultRealm()
-               request = urllib_request.Request(url)
-               request.add_header('User-Agent', 'Gentoo Portage')
-               if if_modified_since:
-                       request.add_header('If-Modified-Since', 
_timestamp_to_http(if_modified_since))
-               if parse_result.username is not None:
-                       password_manager.add_password(None, url, 
parse_result.username, parse_result.password)
-               auth_handler = CompressedResponseProcessor(password_manager)
-               opener = urllib_request.build_opener(auth_handler)
-               hdl = opener.open(request)
-               if hdl.headers.get('last-modified', ''):
-                       try:
-                               add_header = hdl.headers.add_header
-                       except AttributeError:
-                               # Python 2
-                               add_header = hdl.headers.addheader
-                       add_header('timestamp', 
_http_to_timestamp(hdl.headers.get('last-modified')))
-               return hdl
+
+       netloc = parse_result.netloc.rpartition('@')[-1]
+       url = urllib_parse.urlunparse((parse_result.scheme, netloc, 
parse_result.path, parse_result.params, parse_result.query, 
parse_result.fragment))
+       password_manager = urllib_request.HTTPPasswordMgrWithDefaultRealm()
+       request = urllib_request.Request(url)
+       request.add_header('User-Agent', 'Gentoo Portage')
+       if if_modified_since:
+               request.add_header('If-Modified-Since', 
_timestamp_to_http(if_modified_since))
+       if parse_result.username is not None:
+               password_manager.add_password(None, url, parse_result.username, 
parse_result.password)
+       auth_handler = CompressedResponseProcessor(password_manager)
+       opener = urllib_request.build_opener(auth_handler)
+       hdl = opener.open(request)
+       if hdl.headers.get('last-modified', ''):
+               try:
+                       add_header = hdl.headers.add_header
+               except AttributeError:
+                       # Python 2
+                       add_header = hdl.headers.addheader
+               add_header('timestamp', 
_http_to_timestamp(hdl.headers.get('last-modified')))
+       return hdl
 
 def _timestamp_to_http(timestamp):
        dt = datetime.fromtimestamp(float(int(timestamp)+TIMESTAMP_TOLERANCE))

diff --git a/lib/portage/util/changelog.py b/lib/portage/util/changelog.py
index dab756129..362cf7717 100644
--- a/lib/portage/util/changelog.py
+++ b/lib/portage/util/changelog.py
@@ -32,16 +32,15 @@ class ChangeLogTypeSort(str):
 
                if first == "EBUILD":
                        return True
-               elif first == "MISC":
+               if first == "MISC":
                        return second in ("EBUILD",)
-               elif first == "AUX":
+               if first == "AUX":
                        return second in ("EBUILD", "MISC")
-               elif first == "DIST":
+               if first == "DIST":
                        return second in ("EBUILD", "MISC", "AUX")
-               elif first is None:
+               if first is None:
                        return False
-               else:
-                       raise ValueError("Unknown file type '%s'" % first)
+               raise ValueError("Unknown file type '%s'" % first)
 
        def __lt__(self, other):
                """
@@ -55,7 +54,7 @@ class ChangeLogTypeSort(str):
                # Sort by file type as defined by _file_type_lt().
                if self._file_type_lt(self, other):
                        return True
-               elif self._file_type_lt(other, self):
+               if self._file_type_lt(other, self):
                        return False
 
                # Files have the same type.
@@ -64,6 +63,6 @@ class ChangeLogTypeSort(str):
                        ver = "-".join(pkgsplit(self.file_name[:-7])[1:3])
                        other_ver = 
"-".join(pkgsplit(other.file_name[:-7])[1:3])
                        return vercmp(ver, other_ver) < 0
-               else:
-                       # Sort lexicographically.
-                       return self.file_name < other.file_name
+
+               # Sort lexicographically.
+               return self.file_name < other.file_name

diff --git a/lib/portage/util/futures/_asyncio/__init__.py 
b/lib/portage/util/futures/_asyncio/__init__.py
index c944bfe5e..a902ad895 100644
--- a/lib/portage/util/futures/_asyncio/__init__.py
+++ b/lib/portage/util/futures/_asyncio/__init__.py
@@ -158,7 +158,7 @@ def iscoroutinefunction(func):
        """
        if _compat_coroutine._iscoroutinefunction(func):
                return True
-       elif _real_asyncio.iscoroutinefunction(func):
+       if _real_asyncio.iscoroutinefunction(func):
                return True
        return False
 
@@ -256,5 +256,4 @@ def _safe_loop():
        """
        if portage._internal_caller:
                return _global_event_loop()
-       else:
-               return _EventLoop(main=False)
+       return _EventLoop(main=False)

diff --git a/lib/portage/util/futures/unix_events.py 
b/lib/portage/util/futures/unix_events.py
index 6cd0848f7..16a9e12b7 100644
--- a/lib/portage/util/futures/unix_events.py
+++ b/lib/portage/util/futures/unix_events.py
@@ -433,7 +433,7 @@ class _UnixWritePipeTransport(_FlowControlMixin, 
_WriteTransport):
                                return
                        if n == len(data):
                                return
-                       elif n > 0:
+                       if n > 0:
                                data = memoryview(data)[n:]
                        self._loop.add_writer(self._fileno, self._write_ready)
 
@@ -463,7 +463,7 @@ class _UnixWritePipeTransport(_FlowControlMixin, 
_WriteTransport):
                                        self._loop.remove_reader(self._fileno)
                                        self._call_connection_lost(None)
                                return
-                       elif n > 0:
+                       if n > 0:
                                del self._buffer[:n]
 
        def can_write_eof(self):
@@ -617,10 +617,9 @@ class _PortageChildWatcher(_AbstractChildWatcher):
        def _compute_returncode(self, status):
                if os.WIFSIGNALED(status):
                        return -os.WTERMSIG(status)
-               elif os.WIFEXITED(status):
+               if os.WIFEXITED(status):
                        return os.WEXITSTATUS(status)
-               else:
-                       return status
+               return status
 
        def add_child_handler(self, pid, callback, *args):
                """

diff --git a/lib/portage/util/lafilefixer.py b/lib/portage/util/lafilefixer.py
index a16399315..482762bf7 100644
--- a/lib/portage/util/lafilefixer.py
+++ b/lib/portage/util/lafilefixer.py
@@ -181,5 +181,4 @@ def rewrite_lafile(contents):
 
        if changed:
                return True, contents
-       else:
-               return False, None
+       return False, None

diff --git a/lib/portage/versions.py b/lib/portage/versions.py
index af3ec67d8..317683b17 100644
--- a/lib/portage/versions.py
+++ b/lib/portage/versions.py
@@ -104,10 +104,9 @@ def _get_pv_re(eapi_attrs):
 def ververify(myver, silent=1):
        if ver_regexp.match(myver):
                return True
-       else:
-               if not silent:
-                       print(_("!!! syntax error in version: %s") % myver)
-               return False
+       if not silent:
+               print(_("!!! syntax error in version: %s") % myver)
+       return False
 
 @lru_cache(1024)
 def vercmp(ver1, ver2, silent=1):
@@ -202,9 +201,9 @@ def vercmp(ver1, ver2, silent=1):
        for i in range(0, max(len(list1), len(list2))):
                if len(list1) <= i:
                        return -1
-               elif len(list2) <= i:
+               if len(list2) <= i:
                        return 1
-               elif list1[i] != list2[i]:
+               if list1[i] != list2[i]:
                        a = list1[i]
                        b = list2[i]
                        rval = (a > b) - (a < b)
@@ -472,8 +471,7 @@ def pkgsplit(mypkg, silent=1, eapi=None):
        cat, pn, ver, rev = catpsplit
        if cat is _missing_cat and '/' not in mypkg:
                return (pn, ver, rev)
-       else:
-               return (cat + '/' + pn, ver, rev)
+       return (cat + '/' + pn, ver, rev)
 
 def cpv_getkey(mycpv, eapi=None):
        """Calls catpkgsplit on a cpv and returns only the cp."""
@@ -496,8 +494,7 @@ def cpv_getkey(mycpv, eapi=None):
        mylen = len(myslash)
        if mylen == 2:
                return myslash[0] + "/" + mysplit[0]
-       else:
-               return mysplit[0]
+       return mysplit[0]
 
 def cpv_getversion(mycpv, eapi=None):
        """Returns the v (including revision) from an cpv."""

Reply via email to