← Back to team overview

launchpad-reviewers team mailing list archive

[Merge] ~cjwatson/launchpad:bugbear-unused-loop-variables into launchpad:master

 

Colin Watson has proposed merging ~cjwatson/launchpad:bugbear-unused-loop-variables into launchpad:master.

Commit message:
Remove/rename unused loop variables

Requested reviews:
  Launchpad code reviewers (launchpad-reviewers)

For more details, see:
https://code.launchpad.net/~cjwatson/launchpad/+git/launchpad/+merge/454057

`flake8-bugbear` points out:

  B007: Loop control variable not used within the loop body. If this is intended, start the name with an underscore.

In most cases I just changed the variable name to `_` to ignore it.  In some cases there was already a `from lp import _` that would have been shadowed by that approach, so I added a prefix instead.  In a few cases the code could be simplified in other ways, or the loop variable wasn't actually unused because `flake8-bugbear` was confused by the use of `vars()`.
-- 
Your team Launchpad code reviewers is requested to review the proposed merge of ~cjwatson/launchpad:bugbear-unused-loop-variables into launchpad:master.
diff --git a/charm/launchpad-debian-importer/reactive/launchpad-debian-importer.py b/charm/launchpad-debian-importer/reactive/launchpad-debian-importer.py
index f9c42dd..1446e58 100644
--- a/charm/launchpad-debian-importer/reactive/launchpad-debian-importer.py
+++ b/charm/launchpad-debian-importer/reactive/launchpad-debian-importer.py
@@ -27,7 +27,7 @@ def configure():
     config = get_service_config()
     config["debian_suites"] = yaml.safe_load(config["debian_suites"])
     config["debian_components"] = []
-    for suite, components in config["debian_suites"].items():
+    for _, components in config["debian_suites"].items():
         for component in components:
             if component not in config["debian_components"]:
                 config["debian_components"].append(component)
diff --git a/configs/development/gunicorn.conf.py b/configs/development/gunicorn.conf.py
index e2c2ed5..e8dd59b 100644
--- a/configs/development/gunicorn.conf.py
+++ b/configs/development/gunicorn.conf.py
@@ -10,7 +10,7 @@ CONFIG_DIR = os.path.dirname(__file__)
 def find_files(directory, pattern):
     """Find files in `directory` matching `pattern`."""
     result = []
-    for root, dirs, files in os.walk(directory):
+    for root, _, files in os.walk(directory):
         for basename in files:
             matches = fnmatch(basename, pattern)
             if matches:
diff --git a/database/schema/fti.py b/database/schema/fti.py
index 3bb2342..2177ad0 100755
--- a/database/schema/fti.py
+++ b/database/schema/fti.py
@@ -190,7 +190,7 @@ def sexecute(con, sql):
 
 def nullify(con):
     """Set all fti index columns to NULL"""
-    for table, ignored in ALL_FTI:
+    for table, _ in ALL_FTI:
         table = quote_identifier(table)
         log.info("Removing full text index data from %s", table)
         sexecute(con, "ALTER TABLE %s DISABLE TRIGGER tsvectorupdate" % table)
@@ -205,7 +205,7 @@ def liverebuild(con):
     batch_size = 50
 
     cur = con.cursor()
-    for table, ignored in ALL_FTI:
+    for table, _ in ALL_FTI:
         table = quote_identifier(table)
         cur.execute("SELECT max(id) FROM %s" % table)
         max_id = cur.fetchone()[0]
diff --git a/database/schema/online_fti_updater.py b/database/schema/online_fti_updater.py
index 7712111..26ea97b 100755
--- a/database/schema/online_fti_updater.py
+++ b/database/schema/online_fti_updater.py
@@ -20,14 +20,12 @@ def main():
     con.set_isolation_level(0)  # autocommit
     cur = con.cursor()
 
-    for table, ignored in ALL_FTI:
-        print("Doing %(table)s" % vars(), end="")
-        cur.execute("SELECT id FROM %(table)s" % vars())
+    for table, _ in ALL_FTI:
+        print("Doing %s" % table, end="")
+        cur.execute("SELECT id FROM %s" % table)
         ids = [row[0] for row in cur.fetchall()]
         for id in ids:
-            cur.execute(
-                "UPDATE %(table)s SET fti=NULL WHERE id=%(id)s" % vars()
-            )
+            cur.execute("UPDATE %s SET fti=NULL WHERE id=%s" % (table, id))
             if id % 100 == 0:
                 print(".", end="")
         print()
diff --git a/database/schema/preflight.py b/database/schema/preflight.py
index 5ac9309..f5c42f6 100755
--- a/database/schema/preflight.py
+++ b/database/schema/preflight.py
@@ -310,7 +310,7 @@ class DatabasePreflight:
         """Report what patches are due to be applied from this tree."""
         con = self.lpmain_primary_node.con
         upgrade.log = self.log
-        for patch_num, patch_file in upgrade.get_patchlist(con):
+        for _, patch_file in upgrade.get_patchlist(con):
             self.log.info("%s is pending", os.path.basename(patch_file))
 
     def check_all(self):
@@ -381,7 +381,7 @@ class KillConnectionsPreflight(DatabasePreflight):
                     """
                     % sqlvalues(SYSTEM_USERS)
                 )
-                for pid, datname, usename, ignored in cur.fetchall():
+                for pid, datname, usename, _ in cur.fetchall():
                     all_clear = False
                     if loop_count == num_tries - 1:
                         self.log.fatal(
diff --git a/lib/lp/answers/model/question.py b/lib/lp/answers/model/question.py
index af02476..bd760b9 100644
--- a/lib/lp/answers/model/question.py
+++ b/lib/lp/answers/model/question.py
@@ -1045,7 +1045,7 @@ class QuestionSet:
         # Only packages with open questions are included in the query
         # result, so initialize each package to 0.
         counts = {package: 0 for package in packages}
-        for distro_id, spn_id, open_questions in results:
+        for _, spn_id, open_questions in results:
             # The SourcePackageNames here should already be pre-fetched,
             # so that .get(spn_id) won't issue a DB query.
             sourcepackagename = sourcepackagename_set.get(spn_id)
diff --git a/lib/lp/archivepublisher/publishing.py b/lib/lp/archivepublisher/publishing.py
index 0bb7985..622a07f 100644
--- a/lib/lp/archivepublisher/publishing.py
+++ b/lib/lp/archivepublisher/publishing.py
@@ -1882,7 +1882,7 @@ class DirectoryHash:
         ]
         with open(path, "rb") as in_file:
             for chunk in iter(lambda: in_file.read(256 * 1024), b""):
-                for checksum_file, hashobj in hashes:
+                for _, hashobj in hashes:
                     hashobj.update(chunk)
 
         for checksum_file, hashobj in hashes:
@@ -1894,10 +1894,10 @@ class DirectoryHash:
 
     def add_dir(self, path):
         """Recursively add a directory path to be checksummed."""
-        for dirpath, dirnames, filenames in os.walk(path):
+        for dirpath, _, filenames in os.walk(path):
             for filename in filenames:
                 self.add(os.path.join(dirpath, filename))
 
     def close(self):
-        for checksum_path, checksum_file, archive_hash in self.checksum_hash:
+        for _, checksum_file, _ in self.checksum_hash:
             checksum_file.close()
diff --git a/lib/lp/archivepublisher/scripts/publish_ftpmaster.py b/lib/lp/archivepublisher/scripts/publish_ftpmaster.py
index 1e94d67..df1e6ea 100644
--- a/lib/lp/archivepublisher/scripts/publish_ftpmaster.py
+++ b/lib/lp/archivepublisher/scripts/publish_ftpmaster.py
@@ -351,7 +351,7 @@ class PublishFTPMaster(LaunchpadCronScript):
     def setUpDirs(self):
         """Create archive roots and such if they did not yet exist."""
         for distro_configs in self.configs.values():
-            for archive_purpose, archive_config in distro_configs.items():
+            for archive_config in distro_configs.values():
                 archiveroot = archive_config.archiveroot
                 if not file_exists(archiveroot):
                     self.logger.debug("Creating archive root %s.", archiveroot)
diff --git a/lib/lp/archivepublisher/signing.py b/lib/lp/archivepublisher/signing.py
index cad47f1..36f5681 100644
--- a/lib/lp/archivepublisher/signing.py
+++ b/lib/lp/archivepublisher/signing.py
@@ -282,7 +282,7 @@ class SigningUpload(CustomUpload):
             SigningKeyType.FIT: self.signFit,
         }
 
-        for dirpath, dirnames, filenames in os.walk(self.tmpdir):
+        for dirpath, _, filenames in os.walk(self.tmpdir):
             for filename in filenames:
                 file_path = os.path.join(dirpath, filename)
                 if filename.endswith(".efi"):
diff --git a/lib/lp/archivepublisher/tests/test_publisher.py b/lib/lp/archivepublisher/tests/test_publisher.py
index be57298..b270fa5 100644
--- a/lib/lp/archivepublisher/tests/test_publisher.py
+++ b/lib/lp/archivepublisher/tests/test_publisher.py
@@ -2710,7 +2710,7 @@ class TestPublisher(TestPublisherBase):
         self.assertTrue(
             os.path.exists(os.path.join(self.config.distsroot, expected))
         )
-        for pocket, suffix in pocketsuffix.items():
+        for _, suffix in pocketsuffix.items():
             path = os.path.join(self.config.distsroot, "devel%s" % suffix)
             expected_path = os.path.join(
                 self.config.distsroot, expected + suffix
diff --git a/lib/lp/archivepublisher/tests/test_publisherconfig.py b/lib/lp/archivepublisher/tests/test_publisherconfig.py
index e883dab..960f4eb 100644
--- a/lib/lp/archivepublisher/tests/test_publisherconfig.py
+++ b/lib/lp/archivepublisher/tests/test_publisherconfig.py
@@ -55,7 +55,7 @@ class TestPublisherConfig(TestCaseWithFactory):
         # Only one config for each distro is allowed.
 
         def make_conflicting_configs():
-            for counter in range(2):
+            for _ in range(2):
                 self.factory.makePublisherConfig(self.distribution)
             IStore(PublisherConfig).flush()
 
diff --git a/lib/lp/archivepublisher/tests/test_signing.py b/lib/lp/archivepublisher/tests/test_signing.py
index 26f6500..11259d7 100644
--- a/lib/lp/archivepublisher/tests/test_signing.py
+++ b/lib/lp/archivepublisher/tests/test_signing.py
@@ -71,7 +71,7 @@ class SignedMatches(Matcher):
 
     def match(self, base):
         content = []
-        for root, dirs, files in os.walk(base):
+        for root, _, files in os.walk(base):
             content.extend(
                 [os.path.relpath(os.path.join(root, f), base) for f in files]
             )
diff --git a/lib/lp/archivepublisher/tests/test_sync_signingkeys.py b/lib/lp/archivepublisher/tests/test_sync_signingkeys.py
index 7e8a1bb..e31d8bd 100644
--- a/lib/lp/archivepublisher/tests/test_sync_signingkeys.py
+++ b/lib/lp/archivepublisher/tests/test_sync_signingkeys.py
@@ -87,7 +87,7 @@ class TestSyncSigningKeysScript(TestCaseWithFactory):
         return script
 
     def makeArchives(self):
-        for i in range(10):
+        for _ in range(10):
             self.factory.makeArchive()
         conditions = PublisherConfig.distribution_id == Archive.distribution_id
         return IStore(Archive).find(Archive, conditions).order_by(Archive.id)
diff --git a/lib/lp/archiveuploader/ocirecipeupload.py b/lib/lp/archiveuploader/ocirecipeupload.py
index 6d692f9..55fcffd 100644
--- a/lib/lp/archiveuploader/ocirecipeupload.py
+++ b/lib/lp/archiveuploader/ocirecipeupload.py
@@ -51,7 +51,7 @@ class OCIRecipeUpload:
 
             # Foreach id in digest file, find matching layer
             for single_digest in digests:
-                for diff_id, data in single_digest.items():
+                for _, data in single_digest.items():
                     digest = data["digest"]
                     layer_id = data["layer_id"]
                     layer_path = os.path.join(
diff --git a/lib/lp/archiveuploader/uploadprocessor.py b/lib/lp/archiveuploader/uploadprocessor.py
index 9093bdc..7cda7bc 100644
--- a/lib/lp/archiveuploader/uploadprocessor.py
+++ b/lib/lp/archiveuploader/uploadprocessor.py
@@ -295,7 +295,7 @@ class UploadHandler:
         """
         changes_files = []
 
-        for dirpath, dirnames, filenames in os.walk(self.upload_path):
+        for dirpath, _, filenames in os.walk(self.upload_path):
             relative_path = dirpath[len(self.upload_path) + 1 :]
             for filename in filenames:
                 if filename.endswith(".changes"):
diff --git a/lib/lp/blueprints/browser/tests/test_sprint.py b/lib/lp/blueprints/browser/tests/test_sprint.py
index dadc252..14723d3 100644
--- a/lib/lp/blueprints/browser/tests/test_sprint.py
+++ b/lib/lp/blueprints/browser/tests/test_sprint.py
@@ -27,7 +27,7 @@ class TestSprintIndex(BrowserTestCase):
     def test_query_count(self):
         sprint = self.factory.makeSprint()
         with person_logged_in(sprint.owner):
-            for x in range(30):
+            for _ in range(30):
                 sprint.attend(
                     self.factory.makePerson(),
                     sprint.time_starts,
@@ -39,7 +39,7 @@ class TestSprintIndex(BrowserTestCase):
     def test_blueprint_listing_query_count(self):
         """Set a maximum number of queries for sprint blueprint lists."""
         sprint = self.factory.makeSprint()
-        for count in range(10):
+        for _ in range(10):
             blueprint = self.factory.makeSpecification()
             link = blueprint.linkSprint(sprint, blueprint.owner)
             link.acceptBy(sprint.owner)
@@ -50,7 +50,7 @@ class TestSprintIndex(BrowserTestCase):
     def test_proprietary_blueprint_listing_query_count(self):
         """Set a maximum number of queries for sprint blueprint lists."""
         sprint = self.factory.makeSprint()
-        for count in range(10):
+        for _ in range(10):
             blueprint = self.factory.makeSpecification(
                 information_type=InformationType.PROPRIETARY
             )
diff --git a/lib/lp/blueprints/model/tests/test_sprint.py b/lib/lp/blueprints/model/tests/test_sprint.py
index 5c5ba93..74b44a9 100644
--- a/lib/lp/blueprints/model/tests/test_sprint.py
+++ b/lib/lp/blueprints/model/tests/test_sprint.py
@@ -73,7 +73,7 @@ class TestSpecifications(TestCaseWithFactory):
     def test_specifications_quantity(self):
         # Ensure the quantity controls the maximum number of entries.
         sprint = self.factory.makeSprint()
-        for count in range(10):
+        for _ in range(10):
             self.makeSpec(sprint)
         self.assertEqual(10, sprint.specifications(None).count())
         result = sprint.specifications(None, quantity=None).count()
diff --git a/lib/lp/blueprints/tests/test_specification.py b/lib/lp/blueprints/tests/test_specification.py
index 728bcf5..c0ff34a 100644
--- a/lib/lp/blueprints/tests/test_specification.py
+++ b/lib/lp/blueprints/tests/test_specification.py
@@ -808,7 +808,7 @@ class TestSpecifications(TestCaseWithFactory):
         # Ensure the quantity controls the maximum number of entries.
         context = getUtility(ISpecificationSet)
         product = self.factory.makeProduct()
-        for count in range(10):
+        for _ in range(10):
             self.factory.makeSpecification(product=product)
         self.assertEqual(20, context.specifications(None).count())
         result = context.specifications(None, quantity=None).count()
diff --git a/lib/lp/bugs/browser/bugcomment.py b/lib/lp/bugs/browser/bugcomment.py
index 0f653f6..9306de5 100644
--- a/lib/lp/bugs/browser/bugcomment.py
+++ b/lib/lp/bugs/browser/bugcomment.py
@@ -191,7 +191,7 @@ def group_comments_with_activity(comments, activities):
 
     event_windows = gen_event_windows(events)
     event_windows_grouper = groupby(event_windows, itemgetter(0))
-    for window_index, window_group in event_windows_grouper:
+    for _, window_group in event_windows_grouper:
         window_group = [(kind, event) for (index, kind, event) in window_group]
         for kind, event in window_group:
             if kind is comment_kind:
diff --git a/lib/lp/bugs/browser/bugsubscription.py b/lib/lp/bugs/browser/bugsubscription.py
index eaf3ea6..4514f80 100644
--- a/lib/lp/bugs/browser/bugsubscription.py
+++ b/lib/lp/bugs/browser/bugsubscription.py
@@ -591,7 +591,7 @@ class BugPortletSubscribersWithDetails(LaunchpadView):
         """
         data = []
         details = list(bug.getDirectSubscribersWithDetails())
-        for person, subscribed_by, subscription in details:
+        for person, _subscribed_by, subscription in details:
             can_edit = subscription.canBeUnsubscribedByUser(self.user)
             if person == self.user:
                 # Skip the current user viewing the page.
diff --git a/lib/lp/bugs/browser/tests/test_bug_views.py b/lib/lp/bugs/browser/tests/test_bug_views.py
index b4373ae..8cf8bb6 100644
--- a/lib/lp/bugs/browser/tests/test_bug_views.py
+++ b/lib/lp/bugs/browser/tests/test_bug_views.py
@@ -380,7 +380,7 @@ class TestBugPortletSubscribers(TestCaseWithFactory):
         # number of duplicate bugs.
         user = self.factory.makePerson()
         bug = self.factory.makeBug()
-        for n in range(20):
+        for _ in range(20):
             dupe = self.factory.makeBug()
             removeSecurityProxy(dupe)._markAsDuplicate(bug, set())
             removeSecurityProxy(dupe).subscribe(user, dupe.owner)
@@ -963,7 +963,7 @@ class TestBugActivityView(TestCaseWithFactory):
         ten_minutes_ago = datetime.now(timezone.utc) - timedelta(minutes=10)
         with person_logged_in(bug.owner):
             attachment = self.factory.makeBugAttachment(bug=bug)
-            for i in range(10):
+            for _ in range(10):
                 bug.addChange(
                     BugAttachmentChange(
                         ten_minutes_ago,
diff --git a/lib/lp/bugs/browser/tests/test_bugnomination.py b/lib/lp/bugs/browser/tests/test_bugnomination.py
index b3b2eb6..0575f4f 100644
--- a/lib/lp/bugs/browser/tests/test_bugnomination.py
+++ b/lib/lp/bugs/browser/tests/test_bugnomination.py
@@ -105,7 +105,7 @@ class TestBugNominationView(TestCaseWithFactory):
         )
         # Ensure we have some older series so test data better reflects
         # actual usage.
-        for index in range(3):
+        for _ in range(3):
             self.factory.makeDistroSeries(distribution=distro)
         bug = self.factory.makeBug(target=distro, series=current_series)
         series_bugtask = bug.bugtasks[1]
@@ -125,7 +125,7 @@ class TestBugNominationView(TestCaseWithFactory):
         )
         # Ensure we have some older series so test data better reflects
         # actual usage.
-        for index in range(3):
+        for _ in range(3):
             self.factory.makeDistroSeries(distribution=distro)
         package = self.factory.makeDistributionSourcePackage(
             distribution=distro
@@ -146,7 +146,7 @@ class TestBugNominationView(TestCaseWithFactory):
         current_series = self.factory.makeProductSeries(product=product)
         # Ensure we have some older series so test data better reflects
         # actual usage.
-        for index in range(3):
+        for _ in range(3):
             self.factory.makeProductSeries(product=product)
         bug = self.factory.makeBug(target=product, series=current_series)
         series_bugtask = bug.bugtasks[1]
@@ -190,7 +190,7 @@ class TestBugEditLinks(TestCaseWithFactory):
     def _createBug(self, bug_task_number=1):
         series = self.factory.makeProductSeries()
         bug = self.factory.makeBug(series=series)
-        for i in range(bug_task_number):
+        for _ in range(bug_task_number):
             self.factory.makeBugTask(bug=bug)
         launchbag = getUtility(ILaunchBag)
         launchbag.add(series.product)
diff --git a/lib/lp/bugs/browser/tests/test_bugtarget_tags.py b/lib/lp/bugs/browser/tests/test_bugtarget_tags.py
index 44a15ab..7bcd307 100644
--- a/lib/lp/bugs/browser/tests/test_bugtarget_tags.py
+++ b/lib/lp/bugs/browser/tests/test_bugtarget_tags.py
@@ -67,9 +67,9 @@ class TestBugTargetTags(WithScenarios, TestCaseWithFactory):
     def test_tags_order(self):
         """Test that the tags are ordered by most used first"""
         self.factory.makeBug(target=self.bug_target, tags=["tag-last"])
-        for counter in range(0, 2):
+        for _ in range(0, 2):
             self.factory.makeBug(target=self.bug_target, tags=["tag-middle"])
-        for counter in range(0, 3):
+        for _ in range(0, 3):
             self.factory.makeBug(target=self.bug_target, tags=["tag-first"])
         view = create_view(
             self.view_context, name="+bugtarget-portlet-tags-content"
diff --git a/lib/lp/bugs/browser/tests/test_bugtask.py b/lib/lp/bugs/browser/tests/test_bugtask.py
index af11290..cfa6b9b 100644
--- a/lib/lp/bugs/browser/tests/test_bugtask.py
+++ b/lib/lp/bugs/browser/tests/test_bugtask.py
@@ -638,7 +638,7 @@ class TestBugTasksTableView(TestCaseWithFactory):
         self.view = BugTasksNominationsView(self.bug, LaunchpadTestRequest())
 
     def test_not_many_bugtasks(self):
-        for count in range(10 - len(self.bug.bugtasks) - 1):
+        for _ in range(10 - len(self.bug.bugtasks) - 1):
             self.factory.makeBugTask(bug=self.bug)
         self.view.initialize()
         self.assertFalse(self.view.many_bugtasks)
@@ -648,7 +648,7 @@ class TestBugTasksTableView(TestCaseWithFactory):
         self.assertFalse(row_view.many_bugtasks)
 
     def test_many_bugtasks(self):
-        for count in range(10 - len(self.bug.bugtasks)):
+        for _ in range(10 - len(self.bug.bugtasks)):
             self.factory.makeBugTask(bug=self.bug)
         self.view.initialize()
         self.assertTrue(self.view.many_bugtasks)
@@ -2349,7 +2349,7 @@ class TestBugTaskBatchedCommentsAndActivityView(TestCaseWithFactory):
         bug = self.factory.makeBug()
         with person_logged_in(bug.owner):
             if not comments_only:
-                for i in range(number_of_changes):
+                for _ in range(number_of_changes):
                     change = BugTaskStatusChange(
                         bug.default_bugtask,
                         UTC_NOW,
diff --git a/lib/lp/bugs/browser/tests/test_expose.py b/lib/lp/bugs/browser/tests/test_expose.py
index c846754..36c13f1 100644
--- a/lib/lp/bugs/browser/tests/test_expose.py
+++ b/lib/lp/bugs/browser/tests/test_expose.py
@@ -178,7 +178,7 @@ class TestExposeAdministeredTeams(TestCaseWithFactory):
 
         # Create some new public teams owned by the user, and a private
         # team administered by the user.
-        for i in range(3):
+        for _ in range(3):
             self.factory.makeTeam(owner=self.user)
         pt = self.factory.makeTeam(
             visibility=PersonVisibility.PRIVATE, members=[self.user]
diff --git a/lib/lp/bugs/model/bugnotification.py b/lib/lp/bugs/model/bugnotification.py
index 1eb6fcc..5168c1c 100644
--- a/lib/lp/bugs/model/bugnotification.py
+++ b/lib/lp/bugs/model/bugnotification.py
@@ -146,7 +146,7 @@ class BugNotificationSet:
         pending_notifications = []
         people_ids = set()
         bug_ids = set()
-        for notification, ignore, ignore in results:
+        for notification, _, _ in results:
             if notification.message.datecreated > time_limit:
                 last_omitted_notification = notification
             elif (
diff --git a/lib/lp/bugs/model/tests/test_bug.py b/lib/lp/bugs/model/tests/test_bug.py
index 86c291c..103cf98 100644
--- a/lib/lp/bugs/model/tests/test_bug.py
+++ b/lib/lp/bugs/model/tests/test_bug.py
@@ -191,7 +191,7 @@ class TestBug(TestCaseWithFactory):
     def test_get_direct_subscribers_query_count(self):
         bug = self.factory.makeBug()
         # Make lots of subscribers.
-        for i in range(10):
+        for _ in range(10):
             subscriber = self.factory.makePerson()
             with person_logged_in(subscriber):
                 bug.subscribe(subscriber, subscriber)
@@ -205,10 +205,10 @@ class TestBug(TestCaseWithFactory):
         bug = self.factory.makeBug()
         # Make lots of duplicate bugs.
         previous_dup = None
-        for i in range(10):
+        for _ in range(10):
             dup = self.factory.makeBug()
             # Make lots of subscribers.
-            for j in range(10):
+            for _ in range(10):
                 subscriber = self.factory.makePerson()
                 with person_logged_in(subscriber):
                     dup.subscribe(subscriber, subscriber)
@@ -236,7 +236,7 @@ class TestBug(TestCaseWithFactory):
         return self._get_notifications(BugNotificationStatus.DEFERRED)
 
     def _add_subscribers(self, bug, number):
-        for i in range(number):
+        for _ in range(number):
             subscriber = self.factory.makePerson()
             with person_logged_in(subscriber):
                 bug.subscribe(subscriber, subscriber)
diff --git a/lib/lp/bugs/model/tests/test_bugsummary.py b/lib/lp/bugs/model/tests/test_bugsummary.py
index cfa52d1..de50b73 100644
--- a/lib/lp/bugs/model/tests/test_bugsummary.py
+++ b/lib/lp/bugs/model/tests/test_bugsummary.py
@@ -66,7 +66,7 @@ class TestBugSummary(TestCaseWithFactory):
 
         product = self.factory.makeProduct()
 
-        for count in range(3):
+        for _ in range(3):
             bug = self.factory.makeBug(target=product)
             bug_tag = BugTag(bug=bug, tag=tag)
             self.store.add(bug_tag)
@@ -87,7 +87,7 @@ class TestBugSummary(TestCaseWithFactory):
 
         product = self.factory.makeProduct()
 
-        for count in range(3):
+        for _ in range(3):
             bug = self.factory.makeBug(target=product)
             bug_tag = BugTag(bug=bug, tag=old_tag)
             self.store.add(bug_tag)
@@ -114,7 +114,7 @@ class TestBugSummary(TestCaseWithFactory):
 
         product = self.factory.makeProduct()
 
-        for count in range(3):
+        for _ in range(3):
             bug = self.factory.makeBug(target=product)
             bug_tag = BugTag(bug=bug, tag=tag)
             self.store.add(bug_tag)
diff --git a/lib/lp/bugs/model/tests/test_bugtask.py b/lib/lp/bugs/model/tests/test_bugtask.py
index cca4282..0df9c0b 100644
--- a/lib/lp/bugs/model/tests/test_bugtask.py
+++ b/lib/lp/bugs/model/tests/test_bugtask.py
@@ -1884,7 +1884,7 @@ class TestStatusCountsForProductSeries(TestCaseWithFactory):
         for status in statuses:
             self.factory.makeBug(milestone=self.milestone, status=status)
             self.factory.makeBug(series=self.series, status=status)
-        for i in range(3):
+        for _ in range(3):
             self.factory.makeBug(series=self.series)
         expected = {
             BugTaskStatus.INVALID: 2,
diff --git a/lib/lp/bugs/scripts/bugnotification.py b/lib/lp/bugs/scripts/bugnotification.py
index b7557b3..cac4f2d 100644
--- a/lib/lp/bugs/scripts/bugnotification.py
+++ b/lib/lp/bugs/scripts/bugnotification.py
@@ -300,7 +300,7 @@ def get_bug_and_owner(notification):
 def notification_batches(notifications):
     """Batch notifications for `get_email_notifications`."""
     notifications_grouped = groupby(notifications, get_bug_and_owner)
-    for (bug, person), notification_group in notifications_grouped:
+    for _, notification_group in notifications_grouped:
         batches = notification_comment_batches(notification_group)
         for comment_group, batch in groupby(batches, itemgetter(0)):
             yield [notification for (comment_group, notification) in batch]
diff --git a/lib/lp/bugs/scripts/checkwatches/tests/test_scheduler.py b/lib/lp/bugs/scripts/checkwatches/tests/test_scheduler.py
index e2b256d..8f79761 100644
--- a/lib/lp/bugs/scripts/checkwatches/tests/test_scheduler.py
+++ b/lib/lp/bugs/scripts/checkwatches/tests/test_scheduler.py
@@ -81,7 +81,7 @@ class TestBugWatchScheduler(TestCaseWithFactory):
         # The scheduler only looks at the last 5 activity items, so even
         # if there have been more failures the maximum delay will be 7
         # days.
-        for count in range(10):
+        for _ in range(10):
             self.bug_watch.addActivity(
                 result=BugWatchActivityStatus.BUG_NOT_FOUND
             )
diff --git a/lib/lp/bugs/scripts/tests/test_bugnotification.py b/lib/lp/bugs/scripts/tests/test_bugnotification.py
index 99d9197..e6a8cd9 100644
--- a/lib/lp/bugs/scripts/tests/test_bugnotification.py
+++ b/lib/lp/bugs/scripts/tests/test_bugnotification.py
@@ -316,7 +316,7 @@ class TestGetEmailNotifications(TestCase):
         email_notifications = get_email_notifications(notifications_to_send)
         to_addresses = set()
         sent_notifications = []
-        for notifications, omitted, messages in email_notifications:
+        for notifications, _, messages in email_notifications:
             for message in messages:
                 to_addresses.add(message["to"])
             recipients = {}
@@ -715,11 +715,7 @@ class EmailNotificationTestBase(TestCaseWithFactory):
     def get_messages(self):
         notifications = self.notification_set.getNotificationsToSend()
         email_notifications = get_email_notifications(notifications)
-        for (
-            bug_notifications,
-            omitted_notifications,
-            messages,
-        ) in email_notifications:
+        for _, _, messages in email_notifications:
             for message in messages:
                 yield message, message.get_payload(decode=True)
 
@@ -1408,7 +1404,7 @@ class TestDeferredNotifications(TestCaseWithFactory):
         # Create some deferred notifications and show that processing them
         # puts then in the state where they are ready to send.
         num = 5
-        for i in range(num):
+        for _ in range(num):
             self._make_deferred_notification()
         deferred = self.notification_set.getDeferredNotifications()
         self.assertEqual(num, deferred.count())
@@ -1451,7 +1447,7 @@ class TestSendBugNotifications(TestCaseWithFactory):
         # in the way of sending other notifications.
         set_immediate_mail_delivery(False)
         subscribers = []
-        for i in range(3):
+        for _ in range(3):
             bug = self.factory.makeBug()
             subscriber = self.factory.makePerson()
             subscribers.append(subscriber.preferredemail.email)
@@ -1487,7 +1483,7 @@ class TestSendBugNotifications(TestCaseWithFactory):
             "SMTPException: test requested delivery failure",
             self.oopses[0]["tb_text"],
         )
-        for i, (bug_notifications, _, messages) in enumerate(notifications):
+        for i, (bug_notifications, _, _) in enumerate(notifications):
             for bug_notification in bug_notifications:
                 if i == 1:
                     self.assertEqual(
diff --git a/lib/lp/bugs/tests/bug.py b/lib/lp/bugs/tests/bug.py
index e8e07cf..9798b9b 100644
--- a/lib/lp/bugs/tests/bug.py
+++ b/lib/lp/bugs/tests/bug.py
@@ -93,7 +93,7 @@ def print_remote_bugtasks(content):
     """
     affects_table = find_tags_by_class(content, "listing")[0]
     for span in affects_table.find_all("span"):
-        for key, value in span.attrs.items():
+        for value in span.attrs.values():
             if "bug-remote" in value:
                 target = extract_text(span.find_all_previous("td")[-2])
                 print(target, extract_text(span.find_next("a")))
diff --git a/lib/lp/bugs/tests/externalbugtracker.py b/lib/lp/bugs/tests/externalbugtracker.py
index e0e84db..7e24caa 100644
--- a/lib/lp/bugs/tests/externalbugtracker.py
+++ b/lib/lp/bugs/tests/externalbugtracker.py
@@ -1069,8 +1069,8 @@ class TestBugzillaAPIXMLRPCTransport(TestBugzillaXMLRPCTransport):
         if arguments.get("comment_ids") is not None:
             # We need to return all the comments listed.
             comments_to_return = {}
-            for bug_id, comments in self.bug_comments.items():
-                for comment_number, comment in comments.items():
+            for comments in self.bug_comments.values():
+                for comment in comments.values():
                     if comment["id"] in arguments["comment_ids"]:
                         comments_to_return[comment["id"]] = self._copy_comment(
                             comment, fields_to_return
diff --git a/lib/lp/bugs/tests/test_bug_messages_webservice.py b/lib/lp/bugs/tests/test_bug_messages_webservice.py
index 0e220ed..6282c46 100644
--- a/lib/lp/bugs/tests/test_bug_messages_webservice.py
+++ b/lib/lp/bugs/tests/test_bug_messages_webservice.py
@@ -37,7 +37,7 @@ class TestMessageTraversal(TestCaseWithFactory):
         # Traversal over bug messages attachments has no errors.
         expected_messages = []
         with person_logged_in(bug.owner):
-            for i in range(3):
+            for _ in range(3):
                 att = self.factory.makeBugAttachment(bug)
                 expected_messages.append(att.message.subject)
         bug_url = api_url(bug)
diff --git a/lib/lp/bugs/tests/test_bugnotification.py b/lib/lp/bugs/tests/test_bugnotification.py
index eecc427..8413027 100644
--- a/lib/lp/bugs/tests/test_bugnotification.py
+++ b/lib/lp/bugs/tests/test_bugnotification.py
@@ -589,7 +589,7 @@ class TestGetDeferredNotifications(TestCaseWithFactory):
 
     def test_many_deferred_notification(self):
         num = 5
-        for i in range(num):
+        for _ in range(num):
             self._make_deferred_notification()
         results = self.bns.getDeferredNotifications()
         self.assertEqual(num, results.count())
diff --git a/lib/lp/bugs/tests/test_bugs_webservice.py b/lib/lp/bugs/tests/test_bugs_webservice.py
index 6851520..9206787 100644
--- a/lib/lp/bugs/tests/test_bugs_webservice.py
+++ b/lib/lp/bugs/tests/test_bugs_webservice.py
@@ -215,7 +215,7 @@ class TestBugScaling(TestCaseWithFactory):
         with_2_count = collector.count
         self.assertEqual(response.status, 200)
         login(USER_EMAIL)
-        for i in range(5):
+        for _ in range(5):
             self.factory.makeBugAttachment(self.bug)
         logout()
         # Second request.
@@ -252,7 +252,7 @@ class TestBugScaling(TestCaseWithFactory):
         with_2_count = collector.count
         self.assertEqual(response.status, 200)
         login(USER_EMAIL)
-        for i in range(50):
+        for _ in range(50):
             self.factory.makeBugComment(bug)
         self.factory.makeBugAttachment(bug)
         logout()
@@ -341,7 +341,7 @@ class TestPostBugWithLargeCollections(TestCaseWithFactory):
         )
         try:
             login(ADMIN_EMAIL)
-            for count in range(snapshot.HARD_LIMIT_FOR_SNAPSHOT + 1):
+            for _ in range(snapshot.HARD_LIMIT_FOR_SNAPSHOT + 1):
                 person = self.factory.makePerson()
                 bug.subscribe(person, person)
             logout()
diff --git a/lib/lp/bugs/tests/test_bugsearch_conjoined.py b/lib/lp/bugs/tests/test_bugsearch_conjoined.py
index f1c5be1..cdb2f82 100644
--- a/lib/lp/bugs/tests/test_bugsearch_conjoined.py
+++ b/lib/lp/bugs/tests/test_bugsearch_conjoined.py
@@ -152,7 +152,7 @@ class TestProjectGroupExcludeConjoinedPrimarySearch(TestSearchBase):
         self.projectgroup = self.factory.makeProject()
         self.bug_count = 2
         self.bug_products = {}
-        for i in range(self.bug_count):
+        for _ in range(self.bug_count):
             product = self.factory.makeProduct(projectgroup=self.projectgroup)
             product_milestone = self.factory.makeMilestone(
                 product=product, name="foo"
@@ -219,7 +219,7 @@ class TestProjectGroupExcludeConjoinedPrimarySearch(TestSearchBase):
         # group doesn't cause a bugtask on another project in the group
         # to be excluded from the project group milestone's bugs.
         extra_bugtasks = 0
-        for bug, product in self.bug_products.items():
+        for bug in self.bug_products:
             extra_bugtasks += 1
             other_product = self.factory.makeProduct(
                 projectgroup=self.projectgroup
diff --git a/lib/lp/bugs/tests/test_bugsubscription.py b/lib/lp/bugs/tests/test_bugsubscription.py
index 9f66aef..f456c3e 100644
--- a/lib/lp/bugs/tests/test_bugsubscription.py
+++ b/lib/lp/bugs/tests/test_bugsubscription.py
@@ -127,7 +127,7 @@ class TestBugSubscription(TestCaseWithFactory):
             )
             self.bug.subscribe(team, team.teamowner)
         with person_logged_in(team_2.teamowner):
-            for i in range(25):
+            for _ in range(25):
                 person = self.factory.makePerson()
                 team_2.addMember(
                     person, team_2.teamowner, status=TeamMembershipStatus.ADMIN
diff --git a/lib/lp/bugs/tests/test_bugtracker.py b/lib/lp/bugs/tests/test_bugtracker.py
index bcc3d1a..bdcc299 100644
--- a/lib/lp/bugs/tests/test_bugtracker.py
+++ b/lib/lp/bugs/tests/test_bugtracker.py
@@ -90,7 +90,7 @@ class BugTrackerTestCase(TestCaseWithFactory):
     def setUp(self):
         super().setUp()
         self.bug_tracker = self.factory.makeBugTracker()
-        for i in range(5):
+        for _ in range(5):
             self.factory.makeBugWatch(bugtracker=self.bug_tracker)
 
         store = Store.of(self.bug_tracker)
diff --git a/lib/lp/bugs/tests/test_bugwatch.py b/lib/lp/bugs/tests/test_bugwatch.py
index a684b0f..d9779d1 100644
--- a/lib/lp/bugs/tests/test_bugwatch.py
+++ b/lib/lp/bugs/tests/test_bugwatch.py
@@ -689,7 +689,7 @@ class TestBugWatchActivityPruner(TestCaseWithFactory):
     def setUp(self):
         super().setUp("foo.bar@xxxxxxxxxxxxx")
         self.bug_watch = self.factory.makeBugWatch()
-        for i in range(MAX_SAMPLE_SIZE + 1):
+        for _ in range(MAX_SAMPLE_SIZE + 1):
             self.bug_watch.addActivity()
         transaction.commit()
 
diff --git a/lib/lp/bugs/tests/test_cve.py b/lib/lp/bugs/tests/test_cve.py
index e444ead..62c0de2 100644
--- a/lib/lp/bugs/tests/test_cve.py
+++ b/lib/lp/bugs/tests/test_cve.py
@@ -34,7 +34,7 @@ class TestCveSet(TestCaseWithFactory):
         self.cves = []
         self.cve_index = 0
         with person_logged_in(self.distroseries.owner):
-            for count in range(4):
+            for _ in range(4):
                 task = self.factory.makeBugTask(target=self.distroseries)
                 bug = task.bug
                 self.bugs.append(bug)
diff --git a/lib/lp/bugs/tests/test_doc.py b/lib/lp/bugs/tests/test_doc.py
index 9b68b88..037f922 100644
--- a/lib/lp/bugs/tests/test_doc.py
+++ b/lib/lp/bugs/tests/test_doc.py
@@ -485,7 +485,7 @@ def test_suite():
     )
 
     # Add special needs tests
-    for key, special_suite in sorted(special.items()):
+    for _, special_suite in sorted(special.items()):
         suite.addTest(special_suite)
 
     # Add tests using default setup/teardown
diff --git a/lib/lp/buildmaster/browser/tests/test_builder_views.py b/lib/lp/buildmaster/browser/tests/test_builder_views.py
index 98446e2..331275e 100644
--- a/lib/lp/buildmaster/browser/tests/test_builder_views.py
+++ b/lib/lp/buildmaster/browser/tests/test_builder_views.py
@@ -51,7 +51,7 @@ class TestgetSpecificJobs(TestCaseWithFactory):
 
     def createBuilds(self):
         builds = []
-        for i in range(2):
+        for _ in range(2):
             builds.append(self.createBinaryPackageBuild())
             builds.append(self.createTranslationTemplateBuild())
             builds.append(self.createSourcePackageRecipeBuild())
diff --git a/lib/lp/buildmaster/tests/test_webservice.py b/lib/lp/buildmaster/tests/test_webservice.py
index a7ec442..9766b65 100644
--- a/lib/lp/buildmaster/tests/test_webservice.py
+++ b/lib/lp/buildmaster/tests/test_webservice.py
@@ -33,7 +33,7 @@ class TestBuildersCollection(TestCaseWithFactory):
 
     def test_list(self):
         names = ["bob", "frog"]
-        for i in range(3):
+        for _ in range(3):
             builder = self.factory.makeBuilder()
             self.factory.makeBinaryPackageBuild().queueBuild().markAsBuilding(
                 builder
diff --git a/lib/lp/charms/tests/test_charmbase.py b/lib/lp/charms/tests/test_charmbase.py
index d392e33..897d5c4 100644
--- a/lib/lp/charms/tests/test_charmbase.py
+++ b/lib/lp/charms/tests/test_charmbase.py
@@ -357,7 +357,7 @@ class TestCharmBaseWebservice(TestCaseWithFactory):
         webservice.default_api_version = "devel"
         distroseries_urls = []
         with celebrity_logged_in("registry_experts"):
-            for i in range(3):
+            for _ in range(3):
                 distroseries = self.factory.makeDistroSeries()
                 distroseries_urls.append(
                     webservice.getAbsoluteUrl(api_url(distroseries))
diff --git a/lib/lp/charms/tests/test_charmrecipe.py b/lib/lp/charms/tests/test_charmrecipe.py
index f646124..b4922dc 100644
--- a/lib/lp/charms/tests/test_charmrecipe.py
+++ b/lib/lp/charms/tests/test_charmrecipe.py
@@ -1417,7 +1417,7 @@ class TestCharmRecipeSet(TestCaseWithFactory):
         owners = [self.factory.makePerson() for i in range(2)]
         recipes = []
         for owner in owners:
-            for i in range(2):
+            for _ in range(2):
                 recipes.append(
                     self.factory.makeCharmRecipe(registrant=owner, owner=owner)
                 )
@@ -1470,7 +1470,7 @@ class TestCharmRecipeSet(TestCaseWithFactory):
         repositories = [self.factory.makeGitRepository() for i in range(2)]
         recipes = []
         for repository in repositories:
-            for i in range(2):
+            for _ in range(2):
                 [ref] = self.factory.makeGitRefs(repository=repository)
                 recipes.append(self.factory.makeCharmRecipe(git_ref=ref))
         recipe_set = getUtility(ICharmRecipeSet)
@@ -1487,7 +1487,7 @@ class TestCharmRecipeSet(TestCaseWithFactory):
         repositories = [self.factory.makeGitRepository() for i in range(2)]
         recipes = []
         for repository in repositories:
-            for i in range(3):
+            for _ in range(3):
                 [ref] = self.factory.makeGitRefs(repository=repository)
                 recipes.append(self.factory.makeCharmRecipe(git_ref=ref))
         recipe_set = getUtility(ICharmRecipeSet)
@@ -1514,7 +1514,7 @@ class TestCharmRecipeSet(TestCaseWithFactory):
         repositories = [self.factory.makeGitRepository() for i in range(2)]
         refs = []
         recipes = []
-        for repository in repositories:
+        for _ in repositories:
             refs.extend(
                 self.factory.makeGitRefs(
                     paths=["refs/heads/master", "refs/heads/other"]
@@ -1796,7 +1796,7 @@ class TestCharmRecipeSet(TestCaseWithFactory):
         paths = []
         refs = []
         for repository in repositories:
-            for i in range(2):
+            for _ in range(2):
                 [ref] = self.factory.makeGitRefs(repository=repository)
                 paths.append(ref.path)
                 refs.append(ref)
diff --git a/lib/lp/charms/tests/test_charmrecipebuild.py b/lib/lp/charms/tests/test_charmrecipebuild.py
index c5903fa..8d13837 100644
--- a/lib/lp/charms/tests/test_charmrecipebuild.py
+++ b/lib/lp/charms/tests/test_charmrecipebuild.py
@@ -240,7 +240,7 @@ class TestCharmRecipeBuild(TestCaseWithFactory):
             status=BuildStatus.FULLYBUILT,
             duration=timedelta(seconds=335),
         )
-        for i in range(3):
+        for _ in range(3):
             self.factory.makeCharmRecipeBuild(
                 requester=self.build.requester,
                 recipe=self.build.recipe,
diff --git a/lib/lp/code/browser/branchlisting.py b/lib/lp/code/browser/branchlisting.py
index f4b5533..721417c 100644
--- a/lib/lp/code/browser/branchlisting.py
+++ b/lib/lp/code/browser/branchlisting.py
@@ -1469,7 +1469,7 @@ class GroupedDistributionSourcePackageBranchesView(
         and merge proposal links for badges.
         """
         visible_branches = []
-        for branches, count in self.series_branches_map.values():
+        for branches, _count in self.series_branches_map.values():
             visible_branches.extend(branches)
         return visible_branches
 
diff --git a/lib/lp/code/browser/gitrepository.py b/lib/lp/code/browser/gitrepository.py
index b413c58..359ed2c 100644
--- a/lib/lp/code/browser/gitrepository.py
+++ b/lib/lp/code/browser/gitrepository.py
@@ -205,7 +205,7 @@ class GitRepositoryNavigation(WebhookTargetNavigationMixin, Navigation):
             ref_segments.append(segments.pop())
             ref = self.context.getRefByPath("/".join(ref_segments))
             if ref is not None:
-                for unused in range(len(ref_segments)):
+                for _unused in range(len(ref_segments)):
                     self.request.stepstogo.consume()
                 return ref
         raise NotFoundError
@@ -1445,7 +1445,7 @@ class GitRepositoryPermissionsView(LaunchpadFormView):
             key=lambda item: (item[1]["action"] != "add", item[2], item[0])
         )
 
-        for ref_pattern, parsed_rule, position in ordered_rules:
+        for ref_pattern, parsed_rule, _position in ordered_rules:
             rule = rule_map.get(parsed_rule["pattern"])
             action = parsed_rule["action"]
             if action not in ("add", "change", "delete"):
diff --git a/lib/lp/code/browser/tests/test_branch.py b/lib/lp/code/browser/tests/test_branch.py
index e65fc77..3935dc8 100644
--- a/lib/lp/code/browser/tests/test_branch.py
+++ b/lib/lp/code/browser/tests/test_branch.py
@@ -564,7 +564,7 @@ class TestBranchView(BrowserTestCase):
             # record linked bug info for use below
             linked_bug_urls = []
             linked_bug_text = []
-            for x in range(0, 2):
+            for _ in range(0, 2):
                 bug = self.factory.makeBug()
                 mp.source_branch.linkBug(bug, branch.owner)
                 linked_bug_urls.append(
@@ -637,7 +637,7 @@ class TestBranchView(BrowserTestCase):
     def test_query_count_landing_candidates(self):
         product = self.factory.makeProduct()
         branch = self.factory.makeBranch(product=product)
-        for i in range(10):
+        for _ in range(10):
             self.factory.makeBranchMergeProposal(target_branch=branch)
         stacked = self.factory.makeBranch(product=product)
         source = self.factory.makeBranch(stacked_on=stacked, product=product)
@@ -657,7 +657,7 @@ class TestBranchView(BrowserTestCase):
     def test_query_count_landing_targets(self):
         product = self.factory.makeProduct()
         branch = self.factory.makeBranch(product=product)
-        for i in range(10):
+        for _ in range(10):
             self.factory.makeBranchMergeProposal(source_branch=branch)
         stacked = self.factory.makeBranch(product=product)
         target = self.factory.makeBranch(stacked_on=stacked, product=product)
@@ -676,7 +676,7 @@ class TestBranchView(BrowserTestCase):
 
     def test_query_count_subscriber_content(self):
         branch = self.factory.makeBranch()
-        for i in range(10):
+        for _ in range(10):
             self.factory.makeBranchSubscription(branch=branch)
         Store.of(branch).flush()
         Store.of(branch).invalidate()
@@ -689,7 +689,7 @@ class TestBranchView(BrowserTestCase):
 
     def test_query_count_index_with_subscribers(self):
         branch = self.factory.makeBranch()
-        for i in range(10):
+        for _ in range(10):
             self.factory.makeBranchSubscription(branch=branch)
         Store.of(branch).flush()
         Store.of(branch).invalidate()
diff --git a/lib/lp/code/browser/tests/test_branchlisting.py b/lib/lp/code/browser/tests/test_branchlisting.py
index 68bdcc5..5424760 100644
--- a/lib/lp/code/browser/tests/test_branchlisting.py
+++ b/lib/lp/code/browser/tests/test_branchlisting.py
@@ -517,7 +517,7 @@ class TestGroupedDistributionSourcePackageBranchesView(TestCaseWithFactory):
         official = []
         # Sort the pocket items so RELEASE is last, and thus first popped.
         pockets = sorted(PackagePublishingPocket.items, reverse=True)
-        for i in range(official_count):
+        for _ in range(official_count):
             branch = branches.pop()
             pocket = pockets.pop()
             SeriesSourcePackageBranchSet.new(
@@ -790,7 +790,7 @@ class TestProjectGroupBranches(TestCaseWithFactory, AjaxBatchNavigationMixin):
         # The Javascript to wire up the ajax batch navigation behaviour is
         # correctly hidden behind a feature flag.
         product = self.factory.makeProduct(projectgroup=self.projectgroup)
-        for i in range(10):
+        for _ in range(10):
             self.factory.makeProductBranch(product=product)
         self._test_ajax_batch_navigation_feature_flag(
             product, view_name="+branches"
diff --git a/lib/lp/code/browser/tests/test_branchmergeproposal.py b/lib/lp/code/browser/tests/test_branchmergeproposal.py
index 3f5e738..fb29e40 100644
--- a/lib/lp/code/browser/tests/test_branchmergeproposal.py
+++ b/lib/lp/code/browser/tests/test_branchmergeproposal.py
@@ -1727,7 +1727,7 @@ class TestBranchMergeProposalView(TestCaseWithFactory):
         bmp.requestReview(review_date)
         revision_date = review_date + timedelta(days=1)
         revisions = []
-        for date in range(2):
+        for _ in range(2):
             revisions.append(
                 add_revision_to_branch(
                     self.factory, bmp.source_branch, revision_date
diff --git a/lib/lp/code/browser/tests/test_branchmergeproposallisting.py b/lib/lp/code/browser/tests/test_branchmergeproposallisting.py
index 6fcc7a2..113f3ba 100644
--- a/lib/lp/code/browser/tests/test_branchmergeproposallisting.py
+++ b/lib/lp/code/browser/tests/test_branchmergeproposallisting.py
@@ -433,7 +433,7 @@ class BranchMergeProposalListingTestMixin:
         if not self.supports_bzr:
             self.skipTest("Context doesn't support Bazaar branches.")
         with admin_logged_in():
-            for i in range(7):
+            for _ in range(7):
                 self.makeBzrMergeProposal()
         flush_database_caches()
         with StormStatementRecorder() as recorder:
@@ -446,7 +446,7 @@ class BranchMergeProposalListingTestMixin:
         if not self.supports_git:
             self.skipTest("Context doesn't support Git repositories.")
         with admin_logged_in():
-            for i in range(7):
+            for _ in range(7):
                 self.makeGitMergeProposal()
         flush_database_caches()
         with StormStatementRecorder() as recorder:
@@ -1089,7 +1089,7 @@ class ActiveReviewsPerformanceMixin:
         # view and a recorder of the queries generated by this page
         # rendering.
         product = self.factory.makeProduct()
-        for i in range(number_of_bmps):
+        for _ in range(number_of_bmps):
             self.createProductBMP(product=product)
         login_person(product.owner)
         flush_database_caches()
diff --git a/lib/lp/code/browser/tests/test_codereviewcomment.py b/lib/lp/code/browser/tests/test_codereviewcomment.py
index 212cfe8..2c6dc81 100644
--- a/lib/lp/code/browser/tests/test_codereviewcomment.py
+++ b/lib/lp/code/browser/tests/test_codereviewcomment.py
@@ -122,7 +122,7 @@ class TestCodeReviewCommentInlineComments(TestCaseWithFactory):
         person = self.factory.makePerson()
         merge_proposal = self.factory.makeBranchMergeProposal()
         with person_logged_in(person):
-            for i in range(5):
+            for _ in range(5):
                 comment = self.factory.makeCodeReviewComment(
                     merge_proposal=merge_proposal
                 )
diff --git a/lib/lp/code/browser/tests/test_gitlisting.py b/lib/lp/code/browser/tests/test_gitlisting.py
index 1fc40a7..b6b0392 100644
--- a/lib/lp/code/browser/tests/test_gitlisting.py
+++ b/lib/lp/code/browser/tests/test_gitlisting.py
@@ -132,10 +132,10 @@ class TestTargetGitListingView:
 
     def test_query_count(self):
         main_repo = self.factory.makeGitRepository(target=self.target)
-        for i in range(10):
+        for _ in range(10):
             self.factory.makeGitRefs(main_repo)
 
-        for i in range(10):
+        for _ in range(10):
             other_repo = self.factory.makeGitRepository(target=self.target)
             self.factory.makeGitRefs(other_repo)
 
diff --git a/lib/lp/code/browser/tests/test_gitref.py b/lib/lp/code/browser/tests/test_gitref.py
index 0c02bac..ed788fe 100644
--- a/lib/lp/code/browser/tests/test_gitref.py
+++ b/lib/lp/code/browser/tests/test_gitref.py
@@ -1267,7 +1267,7 @@ class TestGitRefView(BrowserTestCase):
     def test_query_count_landing_candidates(self):
         project = self.factory.makeProduct()
         [ref] = self.factory.makeGitRefs(target=project)
-        for i in range(10):
+        for _ in range(10):
             self.factory.makeBranchMergeProposalForGit(target_ref=ref)
         [source] = self.factory.makeGitRefs(target=project)
         [prereq] = self.factory.makeGitRefs(target=project)
@@ -1284,7 +1284,7 @@ class TestGitRefView(BrowserTestCase):
     def test_query_count_landing_targets(self):
         project = self.factory.makeProduct()
         [ref] = self.factory.makeGitRefs(target=project)
-        for i in range(10):
+        for _ in range(10):
             self.factory.makeBranchMergeProposalForGit(source_ref=ref)
         [target] = self.factory.makeGitRefs(target=project)
         [prereq] = self.factory.makeGitRefs(target=project)
diff --git a/lib/lp/code/model/branchjob.py b/lib/lp/code/model/branchjob.py
index c08a8c1..e3781f5 100644
--- a/lib/lp/code/model/branchjob.py
+++ b/lib/lp/code/model/branchjob.py
@@ -955,7 +955,7 @@ class RosettaUploadJob(BranchJobDerived):
 
         to_tree.lock_read()
         try:
-            for dir, files in to_tree.walkdirs():
+            for _, files in to_tree.walkdirs():
                 for afile in files:
                     file_path, file_name, file_type = afile[:3]
                     if file_type != "file":
diff --git a/lib/lp/code/model/branchmergeproposal.py b/lib/lp/code/model/branchmergeproposal.py
index 73cae9a..7abdeff 100644
--- a/lib/lp/code/model/branchmergeproposal.py
+++ b/lib/lp/code/model/branchmergeproposal.py
@@ -1514,7 +1514,7 @@ class BranchMergeProposal(StormBase, BugLinkTargetMixin):
         entries.extend(self._getNewerRevisions())
         entries.sort()
         current_group = []
-        for sortkey, entry in entries:
+        for _, entry in entries:
             if ICodeReviewComment.providedBy(entry):
                 if current_group != []:
                     yield current_group
@@ -1743,7 +1743,7 @@ class BranchMergeProposalGetter:
             (CodeReviewVoteReference, Person, CodeReviewComment),
             CodeReviewVoteReference.branch_merge_proposal_id.is_in(ids),
         )
-        for reference, person, comment in results:
+        for reference, _, _ in results:
             result[reference.branch_merge_proposal].append(reference)
         return result
 
diff --git a/lib/lp/code/model/diff.py b/lib/lp/code/model/diff.py
index fd8b8e3..27f9192 100644
--- a/lib/lp/code/model/diff.py
+++ b/lib/lp/code/model/diff.py
@@ -290,7 +290,7 @@ class Diff(StormBase):
         else:
             added_lines_count = 0
             removed_lines_count = 0
-            for path, (added, removed) in diffstat.items():
+            for added, removed in diffstat.values():
                 added_lines_count += added
                 removed_lines_count += removed
         diff = cls(
diff --git a/lib/lp/code/model/tests/test_branch.py b/lib/lp/code/model/tests/test_branch.py
index 6ea7f28..9e6cf93 100644
--- a/lib/lp/code/model/tests/test_branch.py
+++ b/lib/lp/code/model/tests/test_branch.py
@@ -2384,7 +2384,7 @@ class TestCreateBranchRevisionFromIDs(TestCaseWithFactory):
         branch = self.factory.makeAnyBranch()
         revision_to_number = {}
         revision_id_sequence_pairs = []
-        for i in range(10):
+        for _i in range(10):
             rev = self.factory.makeRevision()
             revision_number = self.factory.getUniqueInteger()
             revision_to_number[rev] = revision_number
diff --git a/lib/lp/code/model/tests/test_branchcloud.py b/lib/lp/code/model/tests/test_branchcloud.py
index 1427af3..cb9575c 100644
--- a/lib/lp/code/model/tests/test_branchcloud.py
+++ b/lib/lp/code/model/tests/test_branchcloud.py
@@ -116,7 +116,7 @@ class TestBranchCloud(TestCaseWithFactory):
             delta=timedelta(days=2),
         )
         store = Store.of(product)
-        for i in range(4):
+        for _ in range(4):
             revision = self.factory.makeRevision(
                 revision_date=next(date_generator)
             )
@@ -132,10 +132,10 @@ class TestBranchCloud(TestCaseWithFactory):
         # getProductsWithInfo returns a result set sorted so that the products
         # with the most commits come first.
         product1 = self.factory.makeProduct()
-        for i in range(3):
+        for _ in range(3):
             self.makeBranch(product=product1)
         product2 = self.factory.makeProduct()
-        for i in range(5):
+        for _ in range(5):
             self.makeBranch(product=product2)
         self.assertEqual(
             [product2.name, product1.name],
@@ -147,13 +147,13 @@ class TestBranchCloud(TestCaseWithFactory):
         # number of products in the result set. The products with the fewest
         # branches are discarded first.
         product1 = self.factory.makeProduct()
-        for i in range(3):
+        for _ in range(3):
             self.makeBranch(product=product1)
         product2 = self.factory.makeProduct()
-        for i in range(5):
+        for _ in range(5):
             self.makeBranch(product=product2)
         product3 = self.factory.makeProduct()
-        for i in range(7):
+        for _ in range(7):
             self.makeBranch(product=product3)
         self.assertEqual(
             [product3.name, product2.name],
diff --git a/lib/lp/code/model/tests/test_branchcollection.py b/lib/lp/code/model/tests/test_branchcollection.py
index 8c4e7f7..f48f5c7 100644
--- a/lib/lp/code/model/tests/test_branchcollection.py
+++ b/lib/lp/code/model/tests/test_branchcollection.py
@@ -176,7 +176,7 @@ class TestGenericBranchCollection(TestCaseWithFactory):
         # the collection.
         collection = GenericBranchCollection(self.store)
         self.assertEqual(0, collection.count())
-        for i in range(3):
+        for _ in range(3):
             self.factory.makeAnyBranch()
         self.assertEqual(3, collection.count())
 
@@ -197,7 +197,7 @@ class TestGenericBranchCollection(TestCaseWithFactory):
         depth = 3
         # Create private branches person can see.
         branches = []
-        for i in range(branch_number):
+        for _ in range(branch_number):
             branches.append(
                 self.factory.makeStackedOnBranchChain(
                     owner=person,
@@ -218,7 +218,7 @@ class TestGenericBranchCollection(TestCaseWithFactory):
         depth = 3
         # Create public branches.
         branches = []
-        for i in range(branch_number):
+        for _ in range(branch_number):
             branches.append(self.factory.makeStackedOnBranchChain(depth=depth))
         all_branches = GenericBranchCollection.preloadVisibleStackedOnBranches(
             branches
@@ -231,7 +231,7 @@ class TestGenericBranchCollection(TestCaseWithFactory):
         depth = 3
         # Create public branches.
         branches = []
-        for i in range(branch_number):
+        for _ in range(branch_number):
             branches.append(
                 self.factory.makeStackedOnBranchChain(
                     owner=person, depth=depth
@@ -922,7 +922,7 @@ class TestExtendedBranchRevisionDetails(TestCaseWithFactory):
 
         linked_bugtasks = []
         with person_logged_in(branch.owner):
-            for x in range(0, 2):
+            for _ in range(0, 2):
                 bug = self.factory.makeBug()
                 merge_proposals[0].source_branch.linkBug(bug, branch.owner)
                 linked_bugtasks.append(bug.default_bugtask)
diff --git a/lib/lp/code/model/tests/test_branchmergeproposal.py b/lib/lp/code/model/tests/test_branchmergeproposal.py
index 26780a7..d5229ee 100644
--- a/lib/lp/code/model/tests/test_branchmergeproposal.py
+++ b/lib/lp/code/model/tests/test_branchmergeproposal.py
@@ -2865,7 +2865,7 @@ class TestGetRevisionsSinceReviewStart(TestCaseWithFactory):
             bmp.requestReview(review_date)
         revision_date = review_date + timedelta(days=1)
         revisions = []
-        for date in range(2):
+        for _ in range(2):
             revisions.append(
                 add_revision_to_branch(
                     self.factory, bmp.source_branch, revision_date
diff --git a/lib/lp/code/model/tests/test_branchpuller.py b/lib/lp/code/model/tests/test_branchpuller.py
index d2215ba..c70cb6b 100644
--- a/lib/lp/code/model/tests/test_branchpuller.py
+++ b/lib/lp/code/model/tests/test_branchpuller.py
@@ -118,7 +118,7 @@ class TestMirroringForMirroredBranches(TestMirroringForImportedBranches):
         """If a branch repeatedly fails to mirror, back off exponentially."""
         branch = self.makeAnyBranch()
         num_failures = 3
-        for i in range(num_failures):
+        for _ in range(num_failures):
             branch.requestMirror()
             branch.startMirroring()
             branch.mirrorFailed("No particular reason")
@@ -132,7 +132,7 @@ class TestMirroringForMirroredBranches(TestMirroringForImportedBranches):
         mirroring.
         """
         branch = self.makeAnyBranch()
-        for i in range(self.max_failures):
+        for _ in range(self.max_failures):
             branch.requestMirror()
             branch.startMirroring()
             branch.mirrorFailed("No particular reason")
diff --git a/lib/lp/code/model/tests/test_cibuild.py b/lib/lp/code/model/tests/test_cibuild.py
index ed55b49..b80c3e9 100644
--- a/lib/lp/code/model/tests/test_cibuild.py
+++ b/lib/lp/code/model/tests/test_cibuild.py
@@ -304,7 +304,7 @@ class TestCIBuild(TestCaseWithFactory):
             status=BuildStatus.FULLYBUILT,
             duration=timedelta(seconds=335),
         )
-        for i in range(3):
+        for _ in range(3):
             self.factory.makeCIBuild(
                 git_repository=build.git_repository,
                 distro_arch_series=build.distro_arch_series,
diff --git a/lib/lp/code/model/tests/test_codeimportjob.py b/lib/lp/code/model/tests/test_codeimportjob.py
index 5fb2596..6dd2957 100644
--- a/lib/lp/code/model/tests/test_codeimportjob.py
+++ b/lib/lp/code/model/tests/test_codeimportjob.py
@@ -1064,12 +1064,12 @@ class TestCodeImportJobWorkflowFinishJob(
         intervals = []
         interval = running_job.code_import.effective_update_interval
         expected_intervals = []
-        for i in range(config.codeimport.consecutive_failure_limit - 1):
+        for _ in range(config.codeimport.consecutive_failure_limit - 1):
             expected_intervals.append(interval)
             interval *= 2
         # Fail an import a bunch of times and record how far in the future the
         # next job was scheduled.
-        for i in range(config.codeimport.consecutive_failure_limit - 1):
+        for _ in range(config.codeimport.consecutive_failure_limit - 1):
             code_import = running_job.code_import
             getUtility(ICodeImportJobWorkflow).finishJob(
                 running_job, CodeImportResultStatus.FAILURE, None
@@ -1274,7 +1274,7 @@ class TestCodeImportJobWorkflowFinishJob(
         # times in a row, the import is marked as FAILING.
         code_import = self.factory.makeCodeImport()
         failure_limit = config.codeimport.consecutive_failure_limit
-        for i in range(failure_limit - 1):
+        for _ in range(failure_limit - 1):
             running_job = self.makeRunningJob(code_import)
             getUtility(ICodeImportJobWorkflow).finishJob(
                 running_job, CodeImportResultStatus.FAILURE, None
diff --git a/lib/lp/code/model/tests/test_codereviewinlinecomment.py b/lib/lp/code/model/tests/test_codereviewinlinecomment.py
index 66cb734..8040b03 100644
--- a/lib/lp/code/model/tests/test_codereviewinlinecomment.py
+++ b/lib/lp/code/model/tests/test_codereviewinlinecomment.py
@@ -210,7 +210,7 @@ class TestCodeReviewInlineComment(TestCaseWithFactory):
         expected_relations = {}
         comments = []
         person = self.factory.makePerson()
-        for i in range(5):
+        for _ in range(5):
             comment = self.factory.makeCodeReviewComment()
             comments.append(comment)
             inline_comment = self.makeCodeReviewInlineComment(
diff --git a/lib/lp/code/model/tests/test_gitcollection.py b/lib/lp/code/model/tests/test_gitcollection.py
index 2fa46fc..44ed4fc 100644
--- a/lib/lp/code/model/tests/test_gitcollection.py
+++ b/lib/lp/code/model/tests/test_gitcollection.py
@@ -179,7 +179,7 @@ class TestGenericGitCollection(TestCaseWithFactory):
         # the collection.
         collection = GenericGitCollection(self.store)
         self.assertEqual(0, collection.count())
-        for i in range(3):
+        for _ in range(3):
             self.factory.makeGitRepository()
         self.assertEqual(3, collection.count())
 
diff --git a/lib/lp/code/model/tests/test_gitrepository.py b/lib/lp/code/model/tests/test_gitrepository.py
index 9ee06d9..b4dbef8 100644
--- a/lib/lp/code/model/tests/test_gitrepository.py
+++ b/lib/lp/code/model/tests/test_gitrepository.py
@@ -1867,7 +1867,7 @@ class TestGitRepositoryModificationNotifications(TestCaseWithFactory):
                 getUtility(IGitRepositoryModifiedMailJobSource)
             ).runAll()
         bodies_by_recipient = {}
-        for from_addr, to_addrs, message in stub.test_emails:
+        for _from_addr, to_addrs, message in stub.test_emails:
             body = (
                 email.message_from_bytes(message)
                 .get_payload(decode=True)
@@ -4517,7 +4517,7 @@ class TestGitRepositoryRules(TestCaseWithFactory):
                         prefix="refs/heads/"
                     ),
                 )
-                for i in range(2):
+                for _i in range(2):
                     self.factory.makeGitRuleGrant(rule=rule)
 
         def get_rules():
@@ -5805,7 +5805,7 @@ class TestGitRepositoryWebservice(TestCaseWithFactory):
         self.assertEqual([], response.jsonBody())
         with person_logged_in(person):
             repo = []
-            for i in range(5):
+            for _i in range(5):
                 repo.append(self.factory.makeGitRepository())
             for i in range(3):
                 removeSecurityProxy(repo[i]).loose_object_count = 7000 + i
@@ -5844,9 +5844,9 @@ class TestGitRepositoryWebservice(TestCaseWithFactory):
         self.assertEqual(200, response.status)
         self.assertEqual(0, response.jsonBody())
         with person_logged_in(person):
-            for item in range(5):
+            for _item in range(5):
                 self.factory.makeGitRepository()
-            for item in range(3):
+            for _item in range(3):
                 repo = self.factory.makeGitRepository()
                 removeSecurityProxy(repo).loose_object_count = 7000
                 removeSecurityProxy(repo).pack_count = 43
diff --git a/lib/lp/code/model/tests/test_revision.py b/lib/lp/code/model/tests/test_revision.py
index 02a5aa1..0fac209 100644
--- a/lib/lp/code/model/tests/test_revision.py
+++ b/lib/lp/code/model/tests/test_revision.py
@@ -985,7 +985,7 @@ class TestPruneRevisionCache(RevisionCacheTestCase):
             datetime.now(timezone.utc) - timedelta(days=33),
             delta=timedelta(days=2),
         )
-        for i in range(4):
+        for _ in range(4):
             revision = self.factory.makeRevision(
                 revision_date=next(date_generator)
             )
@@ -1000,7 +1000,7 @@ class TestPruneRevisionCache(RevisionCacheTestCase):
             datetime.now(timezone.utc) - timedelta(days=33),
             delta=timedelta(days=2),
         )
-        for i in range(4):
+        for _ in range(4):
             revision = self.factory.makeRevision(
                 revision_date=next(date_generator)
             )
diff --git a/lib/lp/code/model/tests/test_revisioncache.py b/lib/lp/code/model/tests/test_revisioncache.py
index df03eb9..b355e76 100644
--- a/lib/lp/code/model/tests/test_revisioncache.py
+++ b/lib/lp/code/model/tests/test_revisioncache.py
@@ -89,7 +89,7 @@ class TestRevisionCache(TestCaseWithFactory):
 
     def test_simple_total_count(self):
         # Test that the count does in fact count the revisions we add.
-        for i in range(4):
+        for _ in range(4):
             self.makeCachedRevision()
         cache = getUtility(IRevisionCache)
         self.assertEqual(4, cache.count())
@@ -135,7 +135,7 @@ class TestRevisionCache(TestCaseWithFactory):
             delta=timedelta(days=-2),
         )
         # Make four cached revisions spanning 33, 31, 29, and 27 days ago.
-        for i in range(4):
+        for _ in range(4):
             self.makeCachedRevision(
                 revision=self.factory.makeRevision(revision_date=next(tc))
             )
@@ -363,7 +363,7 @@ class TestRevisionCache(TestCaseWithFactory):
         # If there are multiple revisions with the same revision author text,
         # but not linked to a Launchpad person, then that revision_text is
         # counted as one author.
-        for counter in range(4):
+        for _ in range(4):
             self.makeCachedRevision(
                 revision=self.factory.makeRevision(
                     author="Foo <foo@xxxxxxxxxxx>"
diff --git a/lib/lp/code/model/tests/test_sourcepackagerecipe.py b/lib/lp/code/model/tests/test_sourcepackagerecipe.py
index 63e54ae..715dd9a 100644
--- a/lib/lp/code/model/tests/test_sourcepackagerecipe.py
+++ b/lib/lp/code/model/tests/test_sourcepackagerecipe.py
@@ -292,7 +292,7 @@ class TestSourcePackageRecipeMixin:
 
     def createSourcePackageRecipe(self, number_of_branches=2):
         branches = []
-        for i in range(number_of_branches):
+        for _ in range(number_of_branches):
             branches.append(self.makeBranch())
         sp_recipe = self.makeSourcePackageRecipe(branches=branches)
         transaction.commit()
diff --git a/lib/lp/code/scripts/tests/test_repack_git_repositories.py b/lib/lp/code/scripts/tests/test_repack_git_repositories.py
index 9f2422d..d02c8d3 100644
--- a/lib/lp/code/scripts/tests/test_repack_git_repositories.py
+++ b/lib/lp/code/scripts/tests/test_repack_git_repositories.py
@@ -284,7 +284,7 @@ class TestRequestGitRepack(TestCaseWithFactory):
             repo[i].loose_object_count = 7000
             repo[i].pack_count = 43
 
-        for i in range(3):
+        for _ in range(3):
             repo.append(self.factory.makeGitRepository())
 
         # we should only have 7 candidates at this point
diff --git a/lib/lp/code/tests/helpers.py b/lib/lp/code/tests/helpers.py
index ff8165b..cbe6b9a 100644
--- a/lib/lp/code/tests/helpers.py
+++ b/lib/lp/code/tests/helpers.py
@@ -236,7 +236,7 @@ def make_project_cloud_data(factory, details):
         start_date = last_commit - delta * (num_commits - 1)
         gen = time_counter(start_date, delta)
         commits_each = num_commits // num_authors
-        for committer in range(num_authors - 1):
+        for _ in range(num_authors - 1):
             make_project_branch_with_revisions(
                 factory, gen, project, commits_each
             )
diff --git a/lib/lp/codehosting/scanner/buglinks.py b/lib/lp/codehosting/scanner/buglinks.py
index e016403..bec1fcf 100644
--- a/lib/lp/codehosting/scanner/buglinks.py
+++ b/lib/lp/codehosting/scanner/buglinks.py
@@ -76,7 +76,7 @@ class BugBranchLinker:
         except InvalidBugStatus:
             return
         bug_set = getUtility(IBugSet)
-        for bug_id, status in bug_info.items():
+        for bug_id in bug_info:
             try:
                 bug = bug_set.get(bug_id)
             except NotFoundError:
diff --git a/lib/lp/codehosting/tests/test_rewrite.py b/lib/lp/codehosting/tests/test_rewrite.py
index 28f78b3..a7e1b90 100644
--- a/lib/lp/codehosting/tests/test_rewrite.py
+++ b/lib/lp/codehosting/tests/test_rewrite.py
@@ -404,7 +404,7 @@ class TestBranchRewriterScriptHandlesDisconnects(TestCase):
         # stderr spam, and this keeps happening. We test more than
         # once to ensure that we will keep trying to reconnect even
         # after several failures.
-        for count in range(5):
+        for _ in range(5):
             out = self.request("foo")
             self.assertEqual(out, "NULL")
 
@@ -422,7 +422,7 @@ class TestBranchRewriterScriptHandlesDisconnects(TestCase):
 
         self.spawn()
 
-        for count in range(5):
+        for _ in range(5):
             out = self.request("foo")
             self.assertEqual(out, "NULL")
 
diff --git a/lib/lp/codehosting/upgrade.py b/lib/lp/codehosting/upgrade.py
index 1bffc40..7220492 100755
--- a/lib/lp/codehosting/upgrade.py
+++ b/lib/lp/codehosting/upgrade.py
@@ -188,7 +188,7 @@ class Upgrader:
         repo = self.bzr_branch.repository
         revision_ids = repo.all_revision_ids()
         for tree in repo.revision_trees(revision_ids):
-            for path, entry in tree.iter_entries_by_dir():
+            for _, entry in tree.iter_entries_by_dir():
                 if entry.kind == "tree-reference":
                     return True
         return False
diff --git a/lib/lp/oci/tests/test_ocirecipe.py b/lib/lp/oci/tests/test_ocirecipe.py
index 92d64ac..1850458 100644
--- a/lib/lp/oci/tests/test_ocirecipe.py
+++ b/lib/lp/oci/tests/test_ocirecipe.py
@@ -1080,7 +1080,7 @@ class TestOCIRecipeAccessControl(TestCaseWithFactory, OCIConfigHelperMixin):
             registrant=person,
         )
         recipes = []
-        for i in range(10):
+        for _ in range(10):
             recipes.append(
                 self.factory.makeOCIRecipe(
                     registrant=person,
@@ -1587,7 +1587,7 @@ class TestOCIRecipeSet(TestCaseWithFactory):
         repositories = [self.factory.makeGitRepository() for i in range(2)]
         oci_recipes = []
         for repository in repositories:
-            for i in range(2):
+            for _ in range(2):
                 [ref] = self.factory.makeGitRefs(
                     repository=repository, paths=["refs/heads/v1.0-20.04"]
                 )
@@ -1642,7 +1642,7 @@ class TestOCIRecipeSet(TestCaseWithFactory):
         paths = []
         refs = []
         for repository in repositories:
-            for i in range(2):
+            for _ in range(2):
                 [ref] = self.factory.makeGitRefs(
                     repository=repository, paths=["refs/heads/v1.0-20.04"]
                 )
diff --git a/lib/lp/oci/tests/test_ocirecipebuild.py b/lib/lp/oci/tests/test_ocirecipebuild.py
index d80ee74..9154be2 100644
--- a/lib/lp/oci/tests/test_ocirecipebuild.py
+++ b/lib/lp/oci/tests/test_ocirecipebuild.py
@@ -249,7 +249,7 @@ class TestOCIRecipeBuild(OCIConfigHelperMixin, TestCaseWithFactory):
         oci_build = self.factory.makeOCIRecipeBuild(
             status=BuildStatus.FULLYBUILT, duration=timedelta(seconds=335)
         )
-        for i in range(3):
+        for _ in range(3):
             self.factory.makeOCIRecipeBuild(
                 requester=oci_build.requester,
                 recipe=oci_build.recipe,
diff --git a/lib/lp/registry/browser/person.py b/lib/lp/registry/browser/person.py
index 3bd82ec..6dab8c8 100644
--- a/lib/lp/registry/browser/person.py
+++ b/lib/lp/registry/browser/person.py
@@ -512,7 +512,7 @@ class PersonNavigation(BranchTraversalMixin, Navigation):
         for distro, ppa, segments, redirect in attempts:
             ppa = traverse_named_ppa(self.context, distro, ppa)
             if ppa is not None:
-                for i in range(segments):
+                for _i in range(segments):
                     self.request.stepstogo.consume()
                 if redirect:
                     return self.redirectSubTree(
diff --git a/lib/lp/registry/browser/tests/test_distributionsourcepackage.py b/lib/lp/registry/browser/tests/test_distributionsourcepackage.py
index 2fe3824..c6313c4 100644
--- a/lib/lp/registry/browser/tests/test_distributionsourcepackage.py
+++ b/lib/lp/registry/browser/tests/test_distributionsourcepackage.py
@@ -55,7 +55,7 @@ class TestDistributionSourcePackageChangelogView(TestCaseWithFactory):
         )
         self.assertThat(dsp, changelog_browses_under_limit)
         with celebrity_logged_in("admin"):
-            for i in range(5):
+            for _ in range(5):
                 self.factory.makePackageDiff(
                     to_source=spph.sourcepackagerelease
                 )
diff --git a/lib/lp/registry/browser/tests/test_distroseries.py b/lib/lp/registry/browser/tests/test_distroseries.py
index 40d9d15..2298c5c 100644
--- a/lib/lp/registry/browser/tests/test_distroseries.py
+++ b/lib/lp/registry/browser/tests/test_distroseries.py
@@ -264,21 +264,21 @@ class DistroSeriesIndexFunctionalTestCase(TestCaseWithFactory):
                 )
             )
         first_parent_series = dsps[0].parent_series
-        for i in range(nb_diff_versions):
+        for _ in range(nb_diff_versions):
             diff_type = DistroSeriesDifferenceType.DIFFERENT_VERSIONS
             self.factory.makeDistroSeriesDifference(
                 derived_series=derived_series,
                 difference_type=diff_type,
                 parent_series=first_parent_series,
             )
-        for i in range(nb_diff_child):
+        for _ in range(nb_diff_child):
             diff_type = DistroSeriesDifferenceType.MISSING_FROM_DERIVED_SERIES
             self.factory.makeDistroSeriesDifference(
                 derived_series=derived_series,
                 difference_type=diff_type,
                 parent_series=first_parent_series,
             )
-        for i in range(nb_diff_parent):
+        for _ in range(nb_diff_parent):
             diff_type = DistroSeriesDifferenceType.UNIQUE_TO_DERIVED_SERIES
             self.factory.makeDistroSeriesDifference(
                 derived_series=derived_series,
@@ -1606,7 +1606,7 @@ class TestDistroSeriesLocalDifferences(
         self.assertThat(recorder1, HasQueryCount(LessThan(12)))
 
         # The query count does not increase with the number of upgrades.
-        for index in range(3):
+        for _ in range(3):
             self.makePackageUpgrade(derived_series=derived_series)
         flush_database_caches()
         with StormStatementRecorder() as recorder2:
diff --git a/lib/lp/registry/browser/tests/test_mailinglists.py b/lib/lp/registry/browser/tests/test_mailinglists.py
index 754e694..ed16526 100644
--- a/lib/lp/registry/browser/tests/test_mailinglists.py
+++ b/lib/lp/registry/browser/tests/test_mailinglists.py
@@ -277,7 +277,7 @@ class TeamMailingListModerationViewTestCase(MailingListTestCase):
     def test_batching(self):
         team = self.makeTeamWithMailingList()
         sender, message, held_message = self.makeHeldMessage(team)
-        for i in range(5):
+        for _ in range(5):
             self.makeHeldMessage(team, sender)
         view = create_initialized_view(
             team, name="+mailinglist-moderate", principal=team.teamowner
diff --git a/lib/lp/registry/browser/tests/test_milestone.py b/lib/lp/registry/browser/tests/test_milestone.py
index e0c380e..89fa352 100644
--- a/lib/lp/registry/browser/tests/test_milestone.py
+++ b/lib/lp/registry/browser/tests/test_milestone.py
@@ -399,7 +399,7 @@ class TestProjectMilestoneIndexQueryCount(TestQueryCountBase):
 
     def add_bug(self, count):
         login_person(self.product_owner)
-        for i in range(count):
+        for _ in range(count):
             bug = self.factory.makeBug(target=self.product)
             bug.bugtasks[0].transitionToMilestone(
                 self.milestone, self.product.owner
@@ -537,7 +537,7 @@ class TestProjectGroupMilestoneIndexQueryCount(TestQueryCountBase):
 
     def add_bug(self, count):
         login_person(self.owner)
-        for i in range(count):
+        for _ in range(count):
             bug = self.factory.makeBug(target=self.product_milestone.product)
             bug.bugtasks[0].transitionToMilestone(
                 self.product_milestone, self.owner
@@ -591,7 +591,7 @@ class TestDistributionMilestoneIndexQueryCount(TestQueryCountBase):
 
     def add_bug(self, count):
         login_person(self.owner)
-        for i in range(count):
+        for _ in range(count):
             bug = self.factory.makeBug(target=self.ubuntu)
             distrosourcepackage = self.factory.makeDistributionSourcePackage(
                 distribution=self.ubuntu
@@ -652,7 +652,7 @@ class TestMilestoneTagView(TestQueryCountBase):
 
     def add_bug(self, count):
         with person_logged_in(self.owner):
-            for n in range(count):
+            for _ in range(count):
                 self.factory.makeBug(
                     target=self.product,
                     owner=self.owner,
diff --git a/lib/lp/registry/browser/tests/test_person.py b/lib/lp/registry/browser/tests/test_person.py
index 88bca93..19425f4 100644
--- a/lib/lp/registry/browser/tests/test_person.py
+++ b/lib/lp/registry/browser/tests/test_person.py
@@ -1651,7 +1651,7 @@ class TestPersonRelatedProjectsView(TestCaseWithFactory):
         )
 
     def test_batching(self):
-        for i in range(10):
+        for _ in range(10):
             self.factory.makeProduct(owner=self.user)
         view = create_initialized_view(self.user, "+related-projects")
         next_match = soupmatchers.HTMLContains(
diff --git a/lib/lp/registry/browser/tests/test_person_contact.py b/lib/lp/registry/browser/tests/test_person_contact.py
index 24e1ccd..8661ab0 100644
--- a/lib/lp/registry/browser/tests/test_person_contact.py
+++ b/lib/lp/registry/browser/tests/test_person_contact.py
@@ -149,7 +149,7 @@ class ContactViaWebNotificationRecipientSetTestCase(TestCaseWithFactory):
         sender = self.factory.makePerson()
         user = self.factory.makePerson(name="pting")
         recipient_set = ContactViaWebNotificationRecipientSet(sender, user)
-        for email, recipient in recipient_set.getRecipientPersons():
+        for email, _ in recipient_set.getRecipientPersons():
             reason, rationale = recipient_set.getReason(email)
         self.assertEqual(
             'using the "Contact this user" link on your profile page '
@@ -162,7 +162,7 @@ class ContactViaWebNotificationRecipientSetTestCase(TestCaseWithFactory):
         sender = self.factory.makePerson()
         team = self.factory.makeTeam(name="pting")
         recipient_set = ContactViaWebNotificationRecipientSet(sender, team)
-        for email, recipient in recipient_set.getRecipientPersons():
+        for email, _ in recipient_set.getRecipientPersons():
             reason, rationale = recipient_set.getReason(email)
         self.assertEqual(
             'using the "Contact this team\'s admins" link '
@@ -176,7 +176,7 @@ class ContactViaWebNotificationRecipientSetTestCase(TestCaseWithFactory):
         team = self.factory.makeTeam(name="pting")
         sender = team.teamowner
         recipient_set = ContactViaWebNotificationRecipientSet(sender, team)
-        for email, recipient in recipient_set.getRecipientPersons():
+        for email, _ in recipient_set.getRecipientPersons():
             reason, rationale = recipient_set.getReason(email)
         self.assertEqual(
             "to each member of the Pting team using the "
@@ -281,7 +281,7 @@ class EmailToPersonViewTestCase(TestCaseWithFactory):
         sender = self.factory.makePerson(email="me@xxxxxx")
         old_message = self.factory.makeSignedMessage(email_address="me@xxxxxx")
         authorization = IDirectEmailAuthorization(sender)
-        for action in range(authorization.message_quota):
+        for _ in range(authorization.message_quota):
             authorization.record(old_message)
         return sender
 
diff --git a/lib/lp/registry/browser/tests/test_person_webservice.py b/lib/lp/registry/browser/tests/test_person_webservice.py
index df60d7e..bcea221 100644
--- a/lib/lp/registry/browser/tests/test_person_webservice.py
+++ b/lib/lp/registry/browser/tests/test_person_webservice.py
@@ -324,7 +324,7 @@ class PersonWebServiceTests(TestCaseWithFactory):
         snapshot.HARD_LIMIT_FOR_SNAPSHOT = 3
         try:
             with person_logged_in(owner):
-                for count in range(snapshot.HARD_LIMIT_FOR_SNAPSHOT + 1):
+                for _ in range(snapshot.HARD_LIMIT_FOR_SNAPSHOT + 1):
                     self.factory.makeArchive(owner=team)
                 team_url = api_url(team)
                 new_member_url = api_url(new_member)
diff --git a/lib/lp/registry/browser/tests/test_pillar_sharing.py b/lib/lp/registry/browser/tests/test_pillar_sharing.py
index 43ac94e..1d9cb06 100644
--- a/lib/lp/registry/browser/tests/test_pillar_sharing.py
+++ b/lib/lp/registry/browser/tests/test_pillar_sharing.py
@@ -432,7 +432,7 @@ class PillarSharingViewTestMixin:
         )
         # Add 4 members to the team, so we should have the team owner + 4
         # other members with access to the artifacts.
-        for i in range(4):
+        for _ in range(4):
             self.factory.makePerson(member_of=[team])
 
         items = [
diff --git a/lib/lp/registry/model/person.py b/lib/lp/registry/model/person.py
index 33cd2b9..a99809e 100644
--- a/lib/lp/registry/model/person.py
+++ b/lib/lp/registry/model/person.py
@@ -1099,7 +1099,7 @@ class Person(
         """See `IPerson`."""
         contributions = []
         results = self._getProjectsWithTheMostKarma(user, limit=limit)
-        for product, distro, karma in results:
+        for product, distro, _karma in results:
             pillar = product or distro
             contributions.append(
                 {
@@ -2808,7 +2808,14 @@ class Person(
 
         warnings = set()
         ref_query = []
-        for src_tab, src_col, ref_tab, ref_col, updact, delact in references:
+        for (
+            src_tab,
+            src_col,
+            _ref_tab,
+            _ref_col,
+            _updact,
+            _delact,
+        ) in references:
             if (src_tab, src_col) in skip:
                 continue
             query = (
diff --git a/lib/lp/registry/model/pillar.py b/lib/lp/registry/model/pillar.py
index 14d4fc8..330c396 100644
--- a/lib/lp/registry/model/pillar.py
+++ b/lib/lp/registry/model/pillar.py
@@ -245,9 +245,7 @@ class PillarNameSet:
             )
         pillars = []
         products = []
-        for pillar_name, other, product, projectgroup, distro in result[
-            :limit
-        ]:
+        for pillar_name, _, _, _, _ in result[:limit]:
             pillar = pillar_name.pillar
             if IProduct.providedBy(pillar):
                 products.append(pillar)
diff --git a/lib/lp/registry/model/product.py b/lib/lp/registry/model/product.py
index 1ebe91c..10bd4c6 100644
--- a/lib/lp/registry/model/product.py
+++ b/lib/lp/registry/model/product.py
@@ -1742,7 +1742,7 @@ def get_precached_products(
             release_caches = {}
             all_releases = []
             milestones_and_releases = get_milestones_and_releases(products)
-            for milestone, release, product_id in milestones_and_releases:
+            for milestone, release, _ in milestones_and_releases:
                 release_cache = get_property_cache(release)
                 release_caches[release.id] = release_cache
                 if not hasattr(release_cache, "files"):
diff --git a/lib/lp/registry/personmerge.py b/lib/lp/registry/personmerge.py
index 2787bc2..cd412e9 100644
--- a/lib/lp/registry/personmerge.py
+++ b/lib/lp/registry/personmerge.py
@@ -1192,7 +1192,7 @@ def merge_people(from_person, to_person, reviewer, delete=False):
     # Sanity check. If we have a reference that participates in a
     # UNIQUE index, it must have already been handled by this point.
     # We can tell this by looking at the skip list.
-    for src_tab, src_col, ref_tab, ref_col, updact, delact in references:
+    for src_tab, src_col, ref_tab, ref_col, _, _ in references:
         uniques = postgresql.listUniques(cur, src_tab, src_col)
         if len(uniques) > 0 and (src_tab, src_col) not in skip:
             raise NotImplementedError(
@@ -1202,7 +1202,7 @@ def merge_people(from_person, to_person, reviewer, delete=False):
             )
 
     # Handle all simple cases
-    for src_tab, src_col, ref_tab, ref_col, updact, delact in references:
+    for src_tab, src_col, _, _, _, _ in references:
         if (src_tab, src_col) in skip:
             continue
         cur.execute(
diff --git a/lib/lp/registry/scripts/tests/test_populate_distroseriesdiff.py b/lib/lp/registry/scripts/tests/test_populate_distroseriesdiff.py
index 4038633..23219c5 100644
--- a/lib/lp/registry/scripts/tests/test_populate_distroseriesdiff.py
+++ b/lib/lp/registry/scripts/tests/test_populate_distroseriesdiff.py
@@ -645,7 +645,7 @@ class TestPopulateDistroSeriesDiffScript(TestCaseWithFactory, FactoryHelper):
 
     def test_finds_all_distroseries(self):
         spphs = []
-        for counter in range(2):
+        for _ in range(2):
             dsp = self.makeDerivedDistroSeries()
             spphs.append(self.makeSPPH(dsp.derived_series))
         script = self.makeScript(["--all"])
diff --git a/lib/lp/registry/services/tests/test_sharingservice.py b/lib/lp/registry/services/tests/test_sharingservice.py
index f0a5d13..16ba918 100644
--- a/lib/lp/registry/services/tests/test_sharingservice.py
+++ b/lib/lp/registry/services/tests/test_sharingservice.py
@@ -577,14 +577,14 @@ class TestSharingService(
             )
 
         # Make some grants and check the count.
-        for x in range(5):
+        for _ in range(5):
             makeGrants()
         with StormStatementRecorder() as recorder:
             grantees = list(func(pillar))
         self.assertEqual(11, len(grantees))
         self.assertThat(recorder, HasQueryCount(LessThan(count)))
         # Make some more grants and check again.
-        for x in range(5):
+        for _ in range(5):
             makeGrants()
         with StormStatementRecorder() as recorder:
             grantees = list(func(pillar))
@@ -1674,7 +1674,7 @@ class TestSharingService(
         # specifications, ocirecipes, and vulnerabilities.
         bugs = []
         bug_tasks = []
-        for x in range(0, 10):
+        for _ in range(0, 10):
             bug = self.factory.makeBug(
                 target=pillar,
                 owner=pillar.owner,
@@ -1683,7 +1683,7 @@ class TestSharingService(
             bugs.append(bug)
             bug_tasks.append(bug.default_bugtask)
         branches = []
-        for x in range(0, 10):
+        for _ in range(0, 10):
             branch = self._makeBranch(
                 pillar=pillar,
                 owner=pillar.owner,
@@ -1691,7 +1691,7 @@ class TestSharingService(
             )
             branches.append(branch)
         gitrepositories = []
-        for x in range(0, 10):
+        for _ in range(0, 10):
             gitrepository = self._makeGitRepository(
                 pillar=pillar,
                 owner=pillar.owner,
@@ -1700,7 +1700,7 @@ class TestSharingService(
             gitrepositories.append(gitrepository)
         snaps = []
         if IProduct.providedBy(pillar):
-            for x in range(0, 10):
+            for _ in range(0, 10):
                 snap = self.factory.makeSnap(
                     project=pillar,
                     owner=pillar.owner,
@@ -1709,7 +1709,7 @@ class TestSharingService(
                 )
                 snaps.append(snap)
         specs = []
-        for x in range(0, 10):
+        for _ in range(0, 10):
             spec = self._makeSpecification(
                 pillar=pillar,
                 owner=pillar.owner,
@@ -1717,7 +1717,7 @@ class TestSharingService(
             )
             specs.append(spec)
         ocirecipes = []
-        for x in range(0, 10):
+        for _ in range(0, 10):
             ociproject = self.factory.makeOCIProject(
                 pillar=pillar, registrant=pillar.owner
             )
@@ -2119,7 +2119,7 @@ class TestSharingService(
             members=[member_with_access]
         )
         people.append(team_without_access)
-        for x in range(0, 10):
+        for _ in range(0, 10):
             person = self.factory.makePerson()
             people.append(person)
         people.append(team_with_access)
@@ -2156,7 +2156,7 @@ class TestSharingService(
         login_person(owner)
 
         bugs = []
-        for x in range(0, 10):
+        for _ in range(0, 10):
             bug = self.factory.makeBug(
                 target=pillar,
                 owner=owner,
@@ -2164,7 +2164,7 @@ class TestSharingService(
             )
             bugs.append(bug)
         branches = []
-        for x in range(0, 10):
+        for _ in range(0, 10):
             branch = self._makeBranch(
                 pillar=pillar,
                 owner=owner,
@@ -2172,7 +2172,7 @@ class TestSharingService(
             )
             branches.append(branch)
         gitrepositories = []
-        for x in range(0, 10):
+        for _ in range(0, 10):
             gitrepository = self._makeGitRepository(
                 pillar=pillar,
                 owner=owner,
@@ -2180,7 +2180,7 @@ class TestSharingService(
             )
             gitrepositories.append(gitrepository)
         specifications = []
-        for x in range(0, 10):
+        for _ in range(0, 10):
             spec = self._makeSpecification(
                 pillar=pillar,
                 owner=owner,
@@ -2307,7 +2307,7 @@ class TestSharingService(
         )
 
         bugs = []
-        for x in range(0, 10):
+        for _ in range(0, 10):
             bug = self.factory.makeBug(
                 target=pillar,
                 owner=owner,
diff --git a/lib/lp/registry/tests/test_accesspolicy.py b/lib/lp/registry/tests/test_accesspolicy.py
index 6481f78..7e4336a 100644
--- a/lib/lp/registry/tests/test_accesspolicy.py
+++ b/lib/lp/registry/tests/test_accesspolicy.py
@@ -883,7 +883,7 @@ class TestReconcileAccessPolicyArtifacts(TestCaseWithFactory):
         def create_bugs():
             while len(bugs):
                 bugs.pop()
-            for i in range(10):
+            for _ in range(10):
                 bugs.append(self.factory.makeBug())
 
         def reconcile():
diff --git a/lib/lp/registry/tests/test_distroseries.py b/lib/lp/registry/tests/test_distroseries.py
index c7e2111..c6dd967 100644
--- a/lib/lp/registry/tests/test_distroseries.py
+++ b/lib/lp/registry/tests/test_distroseries.py
@@ -340,7 +340,7 @@ class TestDistroSeries(TestCaseWithFactory):
         spec2 = self.factory.makeSpecification(
             distribution=distribution, goal=distroseries
         )
-        for i in range(5):
+        for _ in range(5):
             self.factory.makeSpecificationWorkItem(specification=spec1)
             self.factory.makeSpecificationWorkItem(specification=spec2)
         IStore(spec1.__class__).flush()
diff --git a/lib/lp/registry/tests/test_distroseries_vocabularies.py b/lib/lp/registry/tests/test_distroseries_vocabularies.py
index 322adf2..2fc9e27 100644
--- a/lib/lp/registry/tests/test_distroseries_vocabularies.py
+++ b/lib/lp/registry/tests/test_distroseries_vocabularies.py
@@ -216,7 +216,7 @@ class TestDistroSeriesDerivationVocabulary(TestCaseWithFactory):
         self.assertEqual(expected_distroseries, observed_distroseries)
 
     def test_queries_for_distribution_with_non_derived_series(self):
-        for index in range(10):
+        for _ in range(10):
             self.factory.makeDistroSeries()
         distribution = self.factory.makeDistribution()
         distroseries = self.factory.makeDistroSeries(distribution=distribution)
@@ -231,7 +231,7 @@ class TestDistroSeriesDerivationVocabulary(TestCaseWithFactory):
             self.assertThat(recorder, HasQueryCount(Equals(2)))
 
     def test_queries_for_distribution_with_derived_series(self):
-        for index in range(10):
+        for _ in range(10):
             self.factory.makeDistroSeries()
         distribution = self.factory.makeDistribution()
         parent_distroseries = self.factory.makeDistroSeries()
diff --git a/lib/lp/registry/tests/test_distroseriesdifference.py b/lib/lp/registry/tests/test_distroseriesdifference.py
index 4530131..cefef7b 100644
--- a/lib/lp/registry/tests/test_distroseriesdifference.py
+++ b/lib/lp/registry/tests/test_distroseriesdifference.py
@@ -455,7 +455,7 @@ class DistroSeriesDifferenceTestCase(TestCaseWithFactory):
         # Helper method to create packages sets.
         packagesets = []
         with celebrity_logged_in("admin"):
-            for i in range(nb_packagesets):
+            for _ in range(nb_packagesets):
                 ps = self.factory.makePackageset(
                     packages=[ds_diff.source_package_name],
                     distroseries=distroseries,
diff --git a/lib/lp/registry/tests/test_milestone.py b/lib/lp/registry/tests/test_milestone.py
index f9ef144..7409c5e 100644
--- a/lib/lp/registry/tests/test_milestone.py
+++ b/lib/lp/registry/tests/test_milestone.py
@@ -294,7 +294,7 @@ class MilestoneSecurityAdaperTestCase(TestCaseWithFactory):
                 )
 
             # They cannot change any attributes.
-            for permission, names in self.expected_set_permissions.items():
+            for names in self.expected_set_permissions.values():
                 self.assertChangeUnauthorized(names, self.public_milestone)
                 self.assertChangeUnauthorized(
                     names, self.proprietary_milestone
@@ -361,7 +361,7 @@ class MilestoneSecurityAdaperTestCase(TestCaseWithFactory):
                 )
 
             # They cannot change attributes.
-            for permission, names in self.expected_set_permissions.items():
+            for names in self.expected_set_permissions.values():
                 self.assertChangeUnauthorized(names, self.public_milestone)
                 self.assertChangeUnauthorized(
                     names, self.proprietary_milestone
@@ -468,7 +468,7 @@ class MilestoneSecurityAdaperTestCase(TestCaseWithFactory):
                 self.assertAccessAuthorized(names, self.proprietary_milestone)
 
             # They can change attributes.
-            for permission, names in self.expected_set_permissions.items():
+            for names in self.expected_set_permissions.values():
                 self.assertChangeAuthorized(names, self.proprietary_milestone)
 
     def test_access_for_product_driver(self):
@@ -477,7 +477,7 @@ class MilestoneSecurityAdaperTestCase(TestCaseWithFactory):
         with person_logged_in(self.proprietary_product_owner):
             self.proprietary_product.driver = driver
         with person_logged_in(driver):
-            for permission, names in self.expected_set_permissions.items():
+            for names in self.expected_set_permissions.values():
                 self.assertChangeAuthorized(names, self.proprietary_milestone)
 
 
@@ -531,7 +531,7 @@ class MilestoneBugTaskSpecificationTest(TestCaseWithFactory):
     def _create_items(self, num, factory, **kwargs):
         items = []
         with person_logged_in(self.owner):
-            for n in range(num):
+            for _ in range(num):
                 items.append(factory(**kwargs))
         return items
 
diff --git a/lib/lp/registry/tests/test_milestonetag.py b/lib/lp/registry/tests/test_milestonetag.py
index 7dd8260..626aea9 100644
--- a/lib/lp/registry/tests/test_milestonetag.py
+++ b/lib/lp/registry/tests/test_milestonetag.py
@@ -107,7 +107,7 @@ class ProjectGroupMilestoneTagTest(TestCaseWithFactory):
     def _create_bugtasks(self, num, milestone=None):
         bugtasks = []
         with person_logged_in(self.owner):
-            for n in range(num):
+            for _ in range(num):
                 bugtask = self.factory.makeBugTask(
                     target=self.product, owner=self.owner
                 )
@@ -119,7 +119,7 @@ class ProjectGroupMilestoneTagTest(TestCaseWithFactory):
     def _create_specifications(self, num, milestone=None):
         specifications = []
         with person_logged_in(self.owner):
-            for n in range(num):
+            for _ in range(num):
                 specification = self.factory.makeSpecification(
                     product=self.product, owner=self.owner, milestone=milestone
                 )
diff --git a/lib/lp/registry/tests/test_notification.py b/lib/lp/registry/tests/test_notification.py
index 7e91bec..913a2bc 100644
--- a/lib/lp/registry/tests/test_notification.py
+++ b/lib/lp/registry/tests/test_notification.py
@@ -62,7 +62,7 @@ class SendDirectContactEmailTestCase(TestCaseWithFactory):
         recipients_set = NotificationRecipientSet()
         old_message = self.factory.makeSignedMessage(email_address="me@xxxxxx")
         authorization = IDirectEmailAuthorization(user)
-        for action in range(authorization.message_quota):
+        for _ in range(authorization.message_quota):
             authorization.record(old_message)
         self.assertRaises(
             QuotaReachedError,
@@ -82,7 +82,7 @@ class SendDirectContactEmailTestCase(TestCaseWithFactory):
         recipients_set = NotificationRecipientSet()
         old_message = self.factory.makeSignedMessage(email_address="me@xxxxxx")
         authorization = IDirectEmailAuthorization(user)
-        for action in range(authorization.message_quota - 1):
+        for _ in range(authorization.message_quota - 1):
             authorization.record(old_message)
         pop_notifications()
         send_direct_contact_email(
diff --git a/lib/lp/registry/tests/test_person.py b/lib/lp/registry/tests/test_person.py
index cb3a5a7..5381103 100644
--- a/lib/lp/registry/tests/test_person.py
+++ b/lib/lp/registry/tests/test_person.py
@@ -2149,7 +2149,7 @@ class TestSpecifications(TestCaseWithFactory):
     def test_specifications_quantity(self):
         # Ensure the quantity controls the maximum number of entries.
         owner = self.factory.makePerson()
-        for count in range(10):
+        for _ in range(10):
             self.factory.makeSpecification(owner=owner)
         self.assertEqual(10, get_specs(owner).count())
         self.assertEqual(10, get_specs(owner, quantity=None).count())
diff --git a/lib/lp/registry/tests/test_product.py b/lib/lp/registry/tests/test_product.py
index 1ef5135..cde2dcd 100644
--- a/lib/lp/registry/tests/test_product.py
+++ b/lib/lp/registry/tests/test_product.py
@@ -2357,7 +2357,7 @@ class TestSpecifications(TestCaseWithFactory):
     def test_specifications_quantity(self):
         # Ensure the quantity controls the maximum number of entries.
         product = self.factory.makeProduct()
-        for count in range(10):
+        for _ in range(10):
             self.factory.makeSpecification(product=product)
         self.assertEqual(10, get_specs(product).count())
         self.assertEqual(10, get_specs(product, quantity=None).count())
diff --git a/lib/lp/registry/tests/test_productseries.py b/lib/lp/registry/tests/test_productseries.py
index 1188c19..37d9d2f 100644
--- a/lib/lp/registry/tests/test_productseries.py
+++ b/lib/lp/registry/tests/test_productseries.py
@@ -887,7 +887,7 @@ class ProductSeriesSecurityAdaperTestCase(TestCaseWithFactory):
                 self.assertAccessUnauthorized(names, self.proprietary_series)
 
             # They cannot change any attributes.
-            for permission, names in self.expected_set_permissions.items():
+            for names in self.expected_set_permissions.values():
                 self.assertChangeUnauthorized(names, self.public_series)
                 self.assertChangeUnauthorized(names, self.proprietary_series)
 
@@ -1047,38 +1047,38 @@ class ProductSeriesSecurityAdaperTestCase(TestCaseWithFactory):
                 self.assertAccessUnauthorized(names, self.proprietary_series)
 
             # They cannot change any attributes.
-            for permission, names in self.expected_set_permissions.items():
+            for names in self.expected_set_permissions.values():
                 self.assertChangeUnauthorized(names, self.proprietary_series)
 
     def test_access_for_product_owner(self):
         # The owner of a project has access to all attributes of
         # a product series.
         with person_logged_in(self.proprietary_product_owner):
-            for permission, names in self.expected_get_permissions.items():
+            for names in self.expected_get_permissions.values():
                 self.assertAccessAuthorized(names, self.proprietary_series)
 
             # They can change all attributes.
-            for permission, names in self.expected_set_permissions.items():
+            for names in self.expected_set_permissions.values():
                 self.assertChangeAuthorized(names, self.proprietary_series)
 
         with person_logged_in(self.public_product.owner):
-            for permission, names in self.expected_get_permissions.items():
+            for names in self.expected_get_permissions.values():
                 self.assertAccessAuthorized(names, self.public_series)
 
             # They can change all attributes.
-            for permission, names in self.expected_set_permissions.items():
+            for names in self.expected_set_permissions.values():
                 self.assertChangeAuthorized(names, self.public_series)
 
     def test_access_for_lp_admins(self):
         # Launchpad admins can access and change any attribute of a series
         # of public and private product.
         with celebrity_logged_in("admin"):
-            for permission, names in self.expected_get_permissions.items():
+            for names in self.expected_get_permissions.values():
                 self.assertAccessAuthorized(names, self.public_series)
                 self.assertAccessAuthorized(names, self.proprietary_series)
 
             # They can change all attributes.
-            for permission, names in self.expected_set_permissions.items():
+            for names in self.expected_set_permissions.values():
                 self.assertChangeAuthorized(names, self.public_series)
                 self.assertChangeAuthorized(names, self.proprietary_series)
 
diff --git a/lib/lp/registry/tests/test_teammembership.py b/lib/lp/registry/tests/test_teammembership.py
index 5a5fb5b..14372cc 100644
--- a/lib/lp/registry/tests/test_teammembership.py
+++ b/lib/lp/registry/tests/test_teammembership.py
@@ -1539,7 +1539,7 @@ class TestCheckTeamParticipationScriptPerformance(TestCaseWithFactory):
         """
         # Create a deeply nested team and member structure.
         team = self.factory.makeTeam()
-        for num in range(10):
+        for _ in range(10):
             another_team = self.factory.makeTeam()
             another_person = self.factory.makePerson()
             with person_logged_in(team.teamowner):
diff --git a/lib/lp/scripts/garbo.py b/lib/lp/scripts/garbo.py
index 06da799..d4fa136 100644
--- a/lib/lp/scripts/garbo.py
+++ b/lib/lp/scripts/garbo.py
@@ -1077,8 +1077,8 @@ class PersonPruner(TunableLoop):
             from_column,
             to_table,
             to_column,
-            uflag,
-            dflag,
+            _,
+            _,
         ) in postgresql.listReferences(cursor(), "person", "id"):
             # Skip things that don't link to Person.id or that link to it from
             # TeamParticipation or EmailAddress, as all Person entries will be
diff --git a/lib/lp/scripts/tests/test_garbo.py b/lib/lp/scripts/tests/test_garbo.py
index 3599ab1..e2bc91b 100644
--- a/lib/lp/scripts/tests/test_garbo.py
+++ b/lib/lp/scripts/tests/test_garbo.py
@@ -196,7 +196,7 @@ class TestBulkPruner(TestCase):
         self.store = IPrimaryStore(CommercialSubscription)
         self.store.execute("CREATE TABLE BulkFoo (id serial PRIMARY KEY)")
 
-        for i in range(10):
+        for _ in range(10):
             self.store.add(BulkFoo())
 
         self.log = logging.getLogger("garbo")
@@ -1177,7 +1177,7 @@ class TestGarbo(FakeAdapterMixin, TestCaseWithFactory):
 
         # Creating a bunch of old stale repositories to be deleted,
         # to make sure the chunk size is being respected.
-        for i in range(5):
+        for _ in range(5):
             repo = removeSecurityProxy(self.factory.makeGitRepository())
             [ref1, ref2] = self.factory.makeGitRefs(
                 repository=repo, paths=["refs/heads/a-20.04", "b"]
@@ -1383,7 +1383,7 @@ class TestGarbo(FakeAdapterMixin, TestCaseWithFactory):
         # between calls.
         switch_dbuser("testadmin")
         potmsgset_pofile = {}
-        for n in range(4):
+        for _ in range(4):
             pofile = self.factory.makePOFile()
             translation_message = self.factory.makeCurrentTranslationMessage(
                 pofile=pofile
@@ -2295,7 +2295,7 @@ class TestGarbo(FakeAdapterMixin, TestCaseWithFactory):
             report=report1, artifact_type=RevisionStatusArtifactType.BINARY
         )
         artifact1_3 = self.factory.makeRevisionStatusArtifact(report=report1)
-        for i in range(0, 5):
+        for _ in range(0, 5):
             self.factory.makeRevisionStatusArtifact(
                 report=report2, artifact_type=RevisionStatusArtifactType.BINARY
             )
diff --git a/lib/lp/scripts/utilities/importpedant.py b/lib/lp/scripts/utilities/importpedant.py
index cc9e459..342fb18 100644
--- a/lib/lp/scripts/utilities/importpedant.py
+++ b/lib/lp/scripts/utilities/importpedant.py
@@ -293,7 +293,7 @@ def report_naughty_imports():
                 sorted_violations, attrgetter("name")
             ):
                 print("You should not import %s into:" % name)
-                for import_into, unused_duplicates_seq in itertools.groupby(
+                for import_into, _ in itertools.groupby(
                     sequence, attrgetter("import_into")
                 ):
                     # Show first occurrence only, to avoid duplicates.
diff --git a/lib/lp/scripts/utilities/warninghandler.py b/lib/lp/scripts/utilities/warninghandler.py
index d5cadb3..81e805e 100644
--- a/lib/lp/scripts/utilities/warninghandler.py
+++ b/lib/lp/scripts/utilities/warninghandler.py
@@ -93,7 +93,7 @@ def find_important_info():
         important_objects = {}
         metadata = {}  # cls -> (filename, lineno, funcname)
 
-        for frame, filename, lineno, func_name, context, lineidx in stack:
+        for frame, filename, lineno, func_name, _, _ in stack:
             try:
                 if (
                     filename.startswith("<doctest ")
diff --git a/lib/lp/services/database/postgresql.py b/lib/lp/services/database/postgresql.py
index afbfcb0..a4aa227 100644
--- a/lib/lp/services/database/postgresql.py
+++ b/lib/lp/services/database/postgresql.py
@@ -290,7 +290,7 @@ def check_indirect_references(references):
     # Sanity check. If we have an indirect reference, it must
     # be ON DELETE CASCADE. We only have one case of this at the moment,
     # but this code ensures we catch any new ones added incorrectly.
-    for src_tab, src_col, ref_tab, ref_col, updact, delact in references:
+    for src_tab, src_col, ref_tab, ref_col, updact, _ in references:
         # If the ref_tab and ref_col is not Person.id, then we have
         # an indirect reference. Ensure the update action is 'CASCADE'
         if ref_tab != "person" and ref_col != "id":
diff --git a/lib/lp/services/database/sqlbase.py b/lib/lp/services/database/sqlbase.py
index f604f4c..a1a34a0 100644
--- a/lib/lp/services/database/sqlbase.py
+++ b/lib/lp/services/database/sqlbase.py
@@ -328,7 +328,7 @@ def flush_database_updates():
     shorthand if you don't already have a store object handy.)
     """
     zstorm = getUtility(IZStorm)
-    for name, store in zstorm.iterstores():
+    for _, store in zstorm.iterstores():
         store.flush()
 
 
@@ -344,7 +344,7 @@ def flush_database_caches():
     all reflect the values in the database.
     """
     zstorm = getUtility(IZStorm)
-    for name, store in zstorm.iterstores():
+    for _, store in zstorm.iterstores():
         store.flush()
         store.invalidate()
 
diff --git a/lib/lp/services/features/flags.py b/lib/lp/services/features/flags.py
index 4ed46ff..f15a6df 100644
--- a/lib/lp/services/features/flags.py
+++ b/lib/lp/services/features/flags.py
@@ -409,7 +409,7 @@ class FeatureController:
     def _currentValueAndScope(self, flag):
         self._needRules()
         if flag in self._rules:
-            for scope, priority, value in self._rules[flag]:
+            for scope, _, value in self._rules[flag]:
                 if self._known_scopes.lookup(scope):
                     self._debugMessage(
                         "feature match flag=%r value=%r scope=%r"
@@ -481,7 +481,7 @@ class FeatureController:
         """Return the flag's value in the default scope."""
         self._needRules()
         if flag in self._rules:
-            for scope, priority, value in self._rules[flag]:
+            for scope, _, value in self._rules[flag]:
                 if scope == "default":
                     return value
         return None
diff --git a/lib/lp/services/gpg/handler.py b/lib/lp/services/gpg/handler.py
index 912474f..bb354e0 100644
--- a/lib/lp/services/gpg/handler.py
+++ b/lib/lp/services/gpg/handler.py
@@ -116,7 +116,7 @@ class GPGHandler:
         """See IGPGHandler."""
         stored_errors = []
 
-        for i in range(3):
+        for _ in range(3):
             try:
                 signature = self.getVerifiedSignature(content, signature)
             except GPGKeyNotFoundError as info:
@@ -255,7 +255,7 @@ class GPGHandler:
         # a secret key.  We can't rely on result.secret_imported here
         # because if there's a secret key which is already imported,
         # result.secret_imported will be 0.
-        for fingerprint, res, status in result.imports:
+        for fingerprint, _, status in result.imports:
             if status & gpgme.IMPORT_SECRET != 0:
                 raise SecretGPGKeyImportDetected(
                     "GPG key '%s' is a secret key." % fingerprint
diff --git a/lib/lp/services/helpers.py b/lib/lp/services/helpers.py
index 0cbaf30..67128a3 100644
--- a/lib/lp/services/helpers.py
+++ b/lib/lp/services/helpers.py
@@ -56,7 +56,7 @@ def text_replaced(text, replacements, _cache={}):
     cachekey = tuple(replacements.items())
     if cachekey not in _cache:
         L = []
-        for find, replace in sorted(
+        for find, _ in sorted(
             replacements.items(), key=lambda item: len(item[0]), reverse=True
         ):
             L.append("(%s)" % re.escape(find))
diff --git a/lib/lp/services/job/tests/test_celeryjob.py b/lib/lp/services/job/tests/test_celeryjob.py
index 5e7d199..ca2e575 100644
--- a/lib/lp/services/job/tests/test_celeryjob.py
+++ b/lib/lp/services/job/tests/test_celeryjob.py
@@ -47,7 +47,7 @@ class TestRunMissingJobs(TestCaseWithFactory):
         """
         from lp.services.job.celeryjob import FindMissingReady
 
-        for x in range(600):
+        for _ in range(600):
             find_missing = FindMissingReady(job_source)
             if len(find_missing.queue_contents) == expected_len:
                 return find_missing
@@ -65,7 +65,7 @@ class TestRunMissingJobs(TestCaseWithFactory):
         """
         from lazr.jobrunner.celerytask import list_queued
 
-        for x in range(600):
+        for _ in range(600):
             actual_len = len(list_queued(app, queues))
             if actual_len == expected_len:
                 return
diff --git a/lib/lp/services/job/tests/test_runner.py b/lib/lp/services/job/tests/test_runner.py
index 889f941..7f1e8f2 100644
--- a/lib/lp/services/job/tests/test_runner.py
+++ b/lib/lp/services/job/tests/test_runner.py
@@ -590,7 +590,7 @@ class StaticJobSource(BaseRunnableJob):
     @classmethod
     def iterReady(cls):
         if not cls.done:
-            for index, args in enumerate(cls.jobs):
+            for index, _ in enumerate(cls.jobs):
                 yield cls.get(index)
         cls.done = True
 
diff --git a/lib/lp/services/librarianserver/librariangc.py b/lib/lp/services/librarianserver/librariangc.py
index aafd7cb..1f362e6 100644
--- a/lib/lp/services/librarianserver/librariangc.py
+++ b/lib/lp/services/librarianserver/librariangc.py
@@ -254,7 +254,7 @@ def merge_duplicates(con):
             WHERE sha1=%(sha1)s AND filesize=%(filesize)s
             ORDER BY datecreated DESC
             """,
-            vars(),
+            {"sha1": sha1, "filesize": filesize},
         )
         dupes = cur.fetchall()
 
@@ -268,7 +268,7 @@ def merge_duplicates(con):
                     SELECT id, filename, mimetype FROM LibraryFileAlias
                     WHERE content = %(dupe_id)s
                     """,
-                    vars(),
+                    {"dupe_id": dupe_id},
                 )
                 for id, filename, mimetype in cur.fetchall():
                     log.debug3("> %d %s %s" % (id, filename, mimetype))
@@ -316,7 +316,7 @@ def merge_duplicates(con):
                 UPDATE LibraryFileAlias SET content=%(prime_id)s
                 WHERE content = %(other_id)s
                 """,
-                vars(),
+                {"other_id": other_id},
             )
         prime_count += 1
         dupe_count += len(dupes)
diff --git a/lib/lp/services/librarianserver/tests/test_db_outage.py b/lib/lp/services/librarianserver/tests/test_db_outage.py
index 023db40..7329243 100644
--- a/lib/lp/services/librarianserver/tests/test_db_outage.py
+++ b/lib/lp/services/librarianserver/tests/test_db_outage.py
@@ -84,7 +84,7 @@ class TestLibrarianDBOutage(TestCase):
         # connections are in use.
         num_librarian_threads = 20
         codes = set()
-        for count in range(num_librarian_threads):
+        for _ in range(num_librarian_threads):
             try:
                 urlopen(self.url).read()
                 codes.add(200)
diff --git a/lib/lp/services/librarianserver/tests/test_swift.py b/lib/lp/services/librarianserver/tests/test_swift.py
index 9e095dd..673bd52 100644
--- a/lib/lp/services/librarianserver/tests/test_swift.py
+++ b/lib/lp/services/librarianserver/tests/test_swift.py
@@ -196,7 +196,7 @@ class TestFeedSwift(TestCase):
 
         old_swift_client = old_swift_fixture.connect()
         try:
-            for lfc, contents in zip(self.lfcs, self.contents):
+            for lfc, _ in zip(self.lfcs, self.contents):
                 container, name = swift.swift_location(lfc.id)
                 self.assertRaises(
                     swiftclient.ClientException,
diff --git a/lib/lp/services/mail/tests/test_mailbox.py b/lib/lp/services/mail/tests/test_mailbox.py
index 08bdfbe..7532680 100644
--- a/lib/lp/services/mail/tests/test_mailbox.py
+++ b/lib/lp/services/mail/tests/test_mailbox.py
@@ -58,6 +58,6 @@ class TestDirectoryMailBox(TestCase):
         self._add_mailfile("bar", "More content")
         self._add_mailfile("baz", "More content")
         box = DirectoryMailBox(self.email_dir)
-        for id, content in box.items():
+        for id, _ in box.items():
             box.delete(id)
         self.assertEqual(0, len(list(box.items())))
diff --git a/lib/lp/services/oauth/tests/test_tokens.py b/lib/lp/services/oauth/tests/test_tokens.py
index ab69dcb..ad1d4ea 100644
--- a/lib/lp/services/oauth/tests/test_tokens.py
+++ b/lib/lp/services/oauth/tests/test_tokens.py
@@ -258,7 +258,7 @@ class TestRequestTokens(TestOAuth):
         """It's possible to get a person's request tokens."""
         person = self.factory.makePerson()
         self.assertEqual(person.oauth_request_tokens.count(), 0)
-        for i in range(0, 3):
+        for _ in range(0, 3):
             self.factory.makeOAuthRequestToken(reviewed_by=person)
         self.assertEqual(person.oauth_request_tokens.count(), 3)
 
@@ -389,7 +389,7 @@ class TestAccessTokens(TestOAuth):
         """It's possible to get a person's access tokens."""
         person = self.factory.makePerson()
         self.assertEqual(person.oauth_access_tokens.count(), 0)
-        for i in range(0, 3):
+        for _ in range(0, 3):
             self.factory.makeOAuthAccessToken(self.consumer, person)
         self.assertEqual(person.oauth_access_tokens.count(), 3)
 
diff --git a/lib/lp/services/osutils.py b/lib/lp/services/osutils.py
index 1a2e78a..5472b79 100644
--- a/lib/lp/services/osutils.py
+++ b/lib/lp/services/osutils.py
@@ -112,7 +112,7 @@ def two_stage_kill(pid, poll_interval=0.1, num_polls=50, get_status=True):
     _kill_may_race(pid, SIGTERM)
 
     # Poll until the process has ended.
-    for i in range(num_polls):
+    for _ in range(num_polls):
         try:
             if get_status:
                 # Reap the child process and get its return value. If it's
diff --git a/lib/lp/services/profile/profile.py b/lib/lp/services/profile/profile.py
index 8d22f5b..7c7cd4b 100644
--- a/lib/lp/services/profile/profile.py
+++ b/lib/lp/services/profile/profile.py
@@ -498,7 +498,7 @@ def end_request(event):
             triggers.items(), key=lambda x: len(x[1]), reverse=True
         )
         top_triggers = []
-        for key, ixs in triggers:
+        for _, ixs in triggers:
             if len(ixs) == 1:
                 break
             info = trace[ixs[0] - 1]["app_stack"][-1].copy()
@@ -649,7 +649,7 @@ def _make_condition_function(condition_string):
     conditions = []
     included = []
     ignored = []
-    for constraint, partition, value in (
+    for constraint, _, value in (
         c.strip().partition(" ") for c in condition_string.upper().split("|")
     ):
         # Process each condition.
diff --git a/lib/lp/services/profile/tests.py b/lib/lp/services/profile/tests.py
index 0b9019f..b34aa7e 100644
--- a/lib/lp/services/profile/tests.py
+++ b/lib/lp/services/profile/tests.py
@@ -741,7 +741,7 @@ class TestBeforeTraverseHandler(TestCleanupProfiler):
 class TestInlineProfiling(BaseRequestEndHandlerTest):
     def make_work(self, count=1):
         def work():
-            for i in range(count):
+            for _ in range(count):
                 profile.start()
                 random.random()
                 profile.stop()
diff --git a/lib/lp/services/scripts/tests/__init__.py b/lib/lp/services/scripts/tests/__init__.py
index 7bcea71..1f50deb 100644
--- a/lib/lp/services/scripts/tests/__init__.py
+++ b/lib/lp/services/scripts/tests/__init__.py
@@ -28,7 +28,7 @@ def find_lp_scripts():
     scripts = []
     for script_location in SCRIPT_LOCATIONS:
         location = os.path.join(LP_TREE, script_location)
-        for path, dirs, filenames in os.walk(location):
+        for path, _, filenames in os.walk(location):
             for filename in filenames:
                 script_path = os.path.join(path, filename)
                 if filename.startswith("_") or not filename.endswith(".py"):
diff --git a/lib/lp/services/spriteutils.py b/lib/lp/services/spriteutils.py
index e1f9e06..9dd1db4 100644
--- a/lib/lp/services/spriteutils.py
+++ b/lib/lp/services/spriteutils.py
@@ -193,7 +193,7 @@ class SpriteUtil:
         # Paste each sprite into the combined image.
         y = 0
         positions = {}
-        for index, sprite in enumerate(self.sprite_info):
+        for sprite in self.sprite_info:
             sprite_image = sprite_images[sprite["filename"]]
             try:
                 position = [0, y]
diff --git a/lib/lp/services/stacktrace.py b/lib/lp/services/stacktrace.py
index 369c65e..dce2786 100644
--- a/lib/lp/services/stacktrace.py
+++ b/lib/lp/services/stacktrace.py
@@ -68,7 +68,7 @@ def format_list(extracted_list):
     whose source text line or supplement or info are not None.
     """
     list = []
-    for filename, lineno, name, line, modname, supp, info in extracted_list:
+    for filename, lineno, name, line, _, supp, info in extracted_list:
         item = []
         item.append('  File "%s", line %d, in %s' % (filename, lineno, name))
         if line:
diff --git a/lib/lp/services/testing/__init__.py b/lib/lp/services/testing/__init__.py
index 6389963..b296875 100644
--- a/lib/lp/services/testing/__init__.py
+++ b/lib/lp/services/testing/__init__.py
@@ -122,7 +122,7 @@ def build_test_suite(
             )
 
     # Add the special doctests.
-    for key, special_suite in sorted(special_tests.items()):
+    for _, special_suite in sorted(special_tests.items()):
         suite.addTest(special_suite)
 
     tests_path = os.path.join(os.path.pardir, "doc")
diff --git a/lib/lp/services/testing/parallel.py b/lib/lp/services/testing/parallel.py
index 4b7e078..063104f 100644
--- a/lib/lp/services/testing/parallel.py
+++ b/lib/lp/services/testing/parallel.py
@@ -21,7 +21,7 @@ def prepare_argv(argv):
     """Remove options from argv that would be added by ListTestCase."""
     result = []
     skipn = 0
-    for pos, arg in enumerate(argv):
+    for arg in argv:
         if skipn:
             skipn -= 1
             continue
diff --git a/lib/lp/services/testing/tests/test_customresult.py b/lib/lp/services/testing/tests/test_customresult.py
index 378da0a..3c1023a 100644
--- a/lib/lp/services/testing/tests/test_customresult.py
+++ b/lib/lp/services/testing/tests/test_customresult.py
@@ -60,7 +60,7 @@ class TestFilterTests(TestCase):
         suite = unittest.TestSuite()
         for t in testnames:
             # Each test will be repeated equal to the number represented.
-            for i in range(int(t)):
+            for _ in range(int(t)):
                 suite.addTest(FakeTestCase(t))
         return suite
 
diff --git a/lib/lp/services/tests/test_command_spawner.py b/lib/lp/services/tests/test_command_spawner.py
index 4c5df5e..1a869c9 100644
--- a/lib/lp/services/tests/test_command_spawner.py
+++ b/lib/lp/services/tests/test_command_spawner.py
@@ -271,7 +271,7 @@ class TestCommandSpawnerAcceptance(TestCase):
 
         processes = 10
         seconds = 0.2
-        for counter in range(processes):
+        for _ in range(processes):
             spawner.start(["/bin/sleep", str(seconds)])
 
         before = datetime.now(timezone.utc)
diff --git a/lib/lp/services/tests/test_timeout.py b/lib/lp/services/tests/test_timeout.py
index ade63eb..017aa1c 100644
--- a/lib/lp/services/tests/test_timeout.py
+++ b/lib/lp/services/tests/test_timeout.py
@@ -62,7 +62,7 @@ class MySimpleXMLRPCServer(xmlrpc.server.SimpleXMLRPCServer):
     allow_reuse_address = True
 
     def serve_2_requests(self):
-        for i in range(2):
+        for _ in range(2):
             self.handle_request()
         self.server_close()
 
diff --git a/lib/lp/services/twistedsupport/tests/test_task.py b/lib/lp/services/twistedsupport/tests/test_task.py
index e4a44d4..3756f81 100644
--- a/lib/lp/services/twistedsupport/tests/test_task.py
+++ b/lib/lp/services/twistedsupport/tests/test_task.py
@@ -591,7 +591,7 @@ class TestParallelLimitedTaskConsumer(TestCase):
         del log[:]
         consumer.taskStarted(self._neverEndingTask)
         self.assertEqual(0, log.count("stop"))
-        for i in range(worker_limit - 1):
+        for _ in range(worker_limit - 1):
             consumer.taskStarted(self._neverEndingTask)
         self.assertEqual(1, log.count("stop"))
 
diff --git a/lib/lp/services/webapp/metazcml.py b/lib/lp/services/webapp/metazcml.py
index f47d3e2..9eb6130 100644
--- a/lib/lp/services/webapp/metazcml.py
+++ b/lib/lp/services/webapp/metazcml.py
@@ -73,7 +73,7 @@ def authorizations(_context, module):
             "module attribute must be a module: %s, %s" % module, type(module)
         )
     provides = IAuthorization
-    for nameinmodule, authorization in inspect.getmembers(
+    for _, authorization in inspect.getmembers(
         module, lambda member: _isAuthorization(module, member)
     ):
         if (
diff --git a/lib/lp/services/webapp/publisher.py b/lib/lp/services/webapp/publisher.py
index bf64b0d..c45cfed 100644
--- a/lib/lp/services/webapp/publisher.py
+++ b/lib/lp/services/webapp/publisher.py
@@ -535,14 +535,7 @@ class LaunchpadView(UserAttributeCache):
         from lp.services.features.flags import flag_info
 
         beta_info = {}
-        for (
-            flag_name,
-            value_domain,
-            documentation,
-            default_behaviour,
-            title,
-            url,
-        ) in flag_info:
+        for flag_name, _, _, _, title, url in flag_info:
             if flag_name not in self.related_features:
                 continue
             # A feature is always in beta if it's not enabled for
diff --git a/lib/lp/services/webapp/tests/test_batching.py b/lib/lp/services/webapp/tests/test_batching.py
index 74978f1..bd3430d 100644
--- a/lib/lp/services/webapp/tests/test_batching.py
+++ b/lib/lp/services/webapp/tests/test_batching.py
@@ -37,7 +37,7 @@ class TestStormRangeFactory(TestCaseWithFactory):
 
     def makeStormResultSet(self):
         bug = self.factory.makeBug()
-        for count in range(5):
+        for _ in range(5):
             person = self.factory.makePerson()
             with person_logged_in(person):
                 bug.markUserAffected(person, True)
@@ -46,7 +46,7 @@ class TestStormRangeFactory(TestCaseWithFactory):
     def makeDecoratedStormResultSet(self):
         bug = self.factory.makeBug()
         with person_logged_in(bug.owner):
-            for count in range(5):
+            for _ in range(5):
                 self.factory.makeBugAttachment(bug=bug, owner=bug.owner)
         result = bug.attachments
         self.assertTrue(zope_isinstance(result, DecoratedResultSet))
@@ -619,7 +619,7 @@ class TestStormRangeFactory(TestCaseWithFactory):
         with person_logged_in(bug.owner):
             for filename in ("file-a", "file-b"):
                 for content_type in ("text/a", "text/b"):
-                    for count in range(2):
+                    for _ in range(2):
                         self.factory.makeBugAttachment(
                             bug=bug,
                             owner=bug.owner,
diff --git a/lib/lp/services/webapp/tests/test_error.py b/lib/lp/services/webapp/tests/test_error.py
index ee15ed4..dfa0290 100644
--- a/lib/lp/services/webapp/tests/test_error.py
+++ b/lib/lp/services/webapp/tests/test_error.py
@@ -98,7 +98,7 @@ class TestDatabaseErrorViews(TestCase):
         Raise a TimeoutException if the connection cannot be established.
         """
         browser = Browser()
-        for i in range(retries):
+        for _ in range(retries):
             try:
                 browser.open(url)
                 return
diff --git a/lib/lp/services/webhooks/model.py b/lib/lp/services/webhooks/model.py
index 5db81e2..a3d6503 100644
--- a/lib/lp/services/webhooks/model.py
+++ b/lib/lp/services/webhooks/model.py
@@ -584,7 +584,7 @@ class WebhookDeliveryJob(WebhookJobDerived):
     @memoize
     def _get_broadcast_addresses(cls):
         addrs = []
-        for net, addresses in psutil.net_if_addrs().items():
+        for addresses in psutil.net_if_addrs().values():
             for i in addresses:
                 try:
                     addrs.append(ipaddress.ip_address(str(i.broadcast)))
diff --git a/lib/lp/services/webservice/tests/test_wadllib.py b/lib/lp/services/webservice/tests/test_wadllib.py
index 1320d9b..e2d73b3 100644
--- a/lib/lp/services/webservice/tests/test_wadllib.py
+++ b/lib/lp/services/webservice/tests/test_wadllib.py
@@ -20,7 +20,7 @@ def test_suite():
 
     # Find all the doctests in wadllib.
     packages = []
-    for dirpath, dirnames, filenames in os.walk(topdir):
+    for dirpath, dirnames, _ in os.walk(topdir):
         if "docs" in dirnames:
             docsdir = os.path.join(dirpath, "docs")[len(topdir) + 1 :]
             packages.append(docsdir)
diff --git a/lib/lp/services/worlddata/tests/test_language.py b/lib/lp/services/worlddata/tests/test_language.py
index e98b522..407487a 100644
--- a/lib/lp/services/worlddata/tests/test_language.py
+++ b/lib/lp/services/worlddata/tests/test_language.py
@@ -46,7 +46,7 @@ class TestTranslatorsCounts(TestCaseWithFactory):
         super().setUp()
         self.translated_lang = self.factory.makeLanguage(pluralforms=None)
         self.untranslated_lang = self.factory.makeLanguage(pluralforms=None)
-        for i in range(3):
+        for _ in range(3):
             translator = self.factory.makePerson()
             translator.addLanguage(self.translated_lang)
             with dbuser("karma"):
diff --git a/lib/lp/snappy/tests/test_snap.py b/lib/lp/snappy/tests/test_snap.py
index 253a91d..5acd69f 100644
--- a/lib/lp/snappy/tests/test_snap.py
+++ b/lib/lp/snappy/tests/test_snap.py
@@ -2463,7 +2463,7 @@ class TestSnapSet(TestCaseWithFactory):
         owners = [self.factory.makePerson() for i in range(2)]
         snaps = []
         for owner in owners:
-            for i in range(2):
+            for _ in range(2):
                 snaps.append(
                     self.factory.makeSnap(registrant=owner, owner=owner)
                 )
@@ -2560,7 +2560,7 @@ class TestSnapSet(TestCaseWithFactory):
         branches = [self.factory.makeAnyBranch() for i in range(2)]
         snaps = []
         for branch in branches:
-            for i in range(2):
+            for _ in range(2):
                 snaps.append(self.factory.makeSnap(branch=branch))
         snap_set = getUtility(ISnapSet)
         self.assertContentEqual(snaps[:2], snap_set.findByBranch(branches[0]))
@@ -2572,7 +2572,7 @@ class TestSnapSet(TestCaseWithFactory):
         repositories = [self.factory.makeGitRepository() for i in range(2)]
         snaps = []
         for repository in repositories:
-            for i in range(2):
+            for _ in range(2):
                 [ref] = self.factory.makeGitRefs(repository=repository)
                 snaps.append(self.factory.makeSnap(git_ref=ref))
         snap_set = getUtility(ISnapSet)
@@ -2588,7 +2588,7 @@ class TestSnapSet(TestCaseWithFactory):
         repositories = [self.factory.makeGitRepository() for i in range(2)]
         snaps = []
         for repository in repositories:
-            for i in range(3):
+            for _ in range(3):
                 [ref] = self.factory.makeGitRefs(repository=repository)
                 snaps.append(self.factory.makeSnap(git_ref=ref))
         snap_set = getUtility(ISnapSet)
@@ -2615,7 +2615,7 @@ class TestSnapSet(TestCaseWithFactory):
         repositories = [self.factory.makeGitRepository() for i in range(2)]
         refs = []
         snaps = []
-        for repository in repositories:
+        for _ in repositories:
             refs.extend(
                 self.factory.makeGitRefs(
                     paths=["refs/heads/master", "refs/heads/other"]
@@ -3403,7 +3403,7 @@ class TestSnapSet(TestCaseWithFactory):
         branches = [self.factory.makeAnyBranch() for i in range(2)]
         snaps = []
         for branch in branches:
-            for i in range(2):
+            for _ in range(2):
                 snaps.append(
                     self.factory.makeSnap(
                         branch=branch, date_created=ONE_DAY_AGO
@@ -3427,7 +3427,7 @@ class TestSnapSet(TestCaseWithFactory):
         paths = []
         refs = []
         for repository in repositories:
-            for i in range(2):
+            for _ in range(2):
                 [ref] = self.factory.makeGitRefs(repository=repository)
                 paths.append(ref.path)
                 refs.append(ref)
diff --git a/lib/lp/snappy/tests/test_snapbuild.py b/lib/lp/snappy/tests/test_snapbuild.py
index 678d6e9..d8b7758 100644
--- a/lib/lp/snappy/tests/test_snapbuild.py
+++ b/lib/lp/snappy/tests/test_snapbuild.py
@@ -279,7 +279,7 @@ class TestSnapBuild(TestCaseWithFactory):
             status=BuildStatus.FULLYBUILT,
             duration=timedelta(seconds=335),
         )
-        for i in range(3):
+        for _ in range(3):
             self.factory.makeSnapBuild(
                 requester=self.build.requester,
                 snap=self.build.snap,
diff --git a/lib/lp/soyuz/adapters/tests/test_overrides.py b/lib/lp/soyuz/adapters/tests/test_overrides.py
index 5b1c24c..4599b51 100644
--- a/lib/lp/soyuz/adapters/tests/test_overrides.py
+++ b/lib/lp/soyuz/adapters/tests/test_overrides.py
@@ -175,7 +175,7 @@ class TestFromExistingOverridePolicy(TestCaseWithFactory):
         spns = []
         distroseries = self.factory.makeDistroSeries()
         pocket = self.factory.getAnyPocket()
-        for i in range(10):
+        for _ in range(10):
             spph = self.factory.makeSourcePackagePublishingHistory(
                 distroseries=distroseries,
                 archive=distroseries.main_archive,
@@ -473,7 +473,7 @@ class TestFromExistingOverridePolicy(TestCaseWithFactory):
         distroseries = distroarchseries.distroseries
         distroseries.nominatedarchindep = distroarchseries
         pocket = self.factory.getAnyPocket()
-        for i in range(10):
+        for _ in range(10):
             bpph = self.factory.makeBinaryPackagePublishingHistory(
                 distroarchseries=distroarchseries,
                 archive=distroseries.main_archive,
@@ -690,7 +690,7 @@ class TestFallbackOverridePolicy(TestCaseWithFactory):
         expected = {spns[0]: SourceOverride(component=universe, new=True)}
         distroseries = self.factory.makeDistroSeries()
         pocket = self.factory.getAnyPocket()
-        for i in range(8):
+        for _ in range(8):
             spph = self.factory.makeSourcePackagePublishingHistory(
                 distroseries=distroseries,
                 archive=distroseries.main_archive,
@@ -732,7 +732,7 @@ class TestFallbackOverridePolicy(TestCaseWithFactory):
         bpn = self.factory.makeBinaryPackageName()
         bpns = []
         expected = {}
-        for i in range(3):
+        for _ in range(3):
             distroarchseries = self.factory.makeDistroArchSeries(
                 distroseries=distroseries
             )
@@ -756,7 +756,7 @@ class TestFallbackOverridePolicy(TestCaseWithFactory):
                 new=False,
                 version=bpph.binarypackagerelease.version,
             )
-        for i in range(2):
+        for _ in range(2):
             distroarchseries = self.factory.makeDistroArchSeries(
                 distroseries=distroseries
             )
diff --git a/lib/lp/soyuz/browser/tests/test_archive_packages.py b/lib/lp/soyuz/browser/tests/test_archive_packages.py
index 81b9586..3f53639 100644
--- a/lib/lp/soyuz/browser/tests/test_archive_packages.py
+++ b/lib/lp/soyuz/browser/tests/test_archive_packages.py
@@ -313,7 +313,7 @@ class TestPPAPackages(TestCaseWithFactory):
         viewer = self.factory.makePerson()
         browser = self.getUserBrowser(user=viewer)
         with person_logged_in(viewer):
-            for i in range(2):
+            for _ in range(2):
                 pkg = self.factory.makeSourcePackagePublishingHistory(
                     archive=ppa
                 )
@@ -350,7 +350,7 @@ class TestPPAPackages(TestCaseWithFactory):
         viewer = self.factory.makePerson()
         browser = self.getUserBrowser(user=viewer)
         with person_logged_in(viewer):
-            for i in range(3):
+            for _ in range(3):
                 pkg = self.factory.makeBinaryPackagePublishingHistory(
                     archive=ppa, distroarchseries=pkg.distroarchseries
                 )
diff --git a/lib/lp/soyuz/browser/tests/test_archivesubscription.py b/lib/lp/soyuz/browser/tests/test_archivesubscription.py
index 81b059b..97fe238 100644
--- a/lib/lp/soyuz/browser/tests/test_archivesubscription.py
+++ b/lib/lp/soyuz/browser/tests/test_archivesubscription.py
@@ -34,7 +34,7 @@ class TestArchiveSubscribersView(TestCaseWithFactory):
                 owner=self.p3a_owner, private=True, name="p3a"
             )
         with person_logged_in(self.p3a_owner):
-            for count in range(3):
+            for _ in range(3):
                 subscriber = self.factory.makePerson()
                 self.private_ppa.newSubscription(subscriber, self.p3a_owner)
 
diff --git a/lib/lp/soyuz/browser/tests/test_build_views.py b/lib/lp/soyuz/browser/tests/test_build_views.py
index 7b9390c..efab0ea 100644
--- a/lib/lp/soyuz/browser/tests/test_build_views.py
+++ b/lib/lp/soyuz/browser/tests/test_build_views.py
@@ -349,7 +349,7 @@ class TestBuildViews(TestCaseWithFactory):
         # The BuildRecordsView can also be used to filter by architecture tag.
         distroseries = self.factory.makeDistroSeries()
         arch_list = []
-        for i in range(5):
+        for _ in range(5):
             das = self.factory.makeDistroArchSeries(distroseries=distroseries)
             arch_list.append(das.architecturetag)
             build = self.factory.makeBinaryPackageBuild(
diff --git a/lib/lp/soyuz/browser/tests/test_queue.py b/lib/lp/soyuz/browser/tests/test_queue.py
index 865df31..b95be3a 100644
--- a/lib/lp/soyuz/browser/tests/test_queue.py
+++ b/lib/lp/soyuz/browser/tests/test_queue.py
@@ -477,7 +477,7 @@ class TestQueueItemsView(TestCaseWithFactory):
         dsc = self.factory.makeLibraryFileAlias(filename="foo_0.1.dsc")
         deb = self.factory.makeLibraryFileAlias(filename="foo.deb")
         transaction.commit()
-        for i in range(5):
+        for _ in range(5):
             uploads.append(self.factory.makeSourcePackageUpload(distroseries))
             sprs.append(uploads[-1].sources[0].sourcepackagerelease)
             sprs[-1].addFile(dsc)
@@ -504,7 +504,7 @@ class TestQueueItemsView(TestCaseWithFactory):
         )
         for i in (0, 2, 3):
             self.factory.makePackageDiff(to_source=sprs[i])
-        for i in range(15):
+        for _ in range(15):
             uploads.append(self.factory.makeBuildPackageUpload(distroseries))
             uploads[-1].builds[0].build.binarypackages[0].addFile(deb)
         queue_admin = self.factory.makeArchiveAdmin(distroseries.main_archive)
@@ -520,7 +520,7 @@ class TestQueueItemsView(TestCaseWithFactory):
         uploads = []
         distroseries = self.factory.makeDistroSeries()
 
-        for i in range(11):
+        for _ in range(11):
             uploads.append(self.factory.makeSourcePackageUpload(distroseries))
         queue_admin = self.factory.makeArchiveAdmin(distroseries.main_archive)
 
diff --git a/lib/lp/soyuz/model/distroseriespackagecache.py b/lib/lp/soyuz/model/distroseriespackagecache.py
index 45a4692..7ed84b6 100644
--- a/lib/lp/soyuz/model/distroseriespackagecache.py
+++ b/lib/lp/soyuz/model/distroseriespackagecache.py
@@ -186,7 +186,7 @@ class DistroSeriesPackageCache(StormBase):
             return
 
         details_map = defaultdict(list)
-        for bpn_id, summary, description, datecreated in all_details:
+        for bpn_id, summary, description, _ in all_details:
             bpn = IStore(BinaryPackageName).get(BinaryPackageName, bpn_id)
             details_map[bpn].append((summary, description))
 
diff --git a/lib/lp/soyuz/scripts/tests/test_copypackage.py b/lib/lp/soyuz/scripts/tests/test_copypackage.py
index e4ad931..5110e4d 100644
--- a/lib/lp/soyuz/scripts/tests/test_copypackage.py
+++ b/lib/lp/soyuz/scripts/tests/test_copypackage.py
@@ -510,7 +510,7 @@ class CopyCheckerQueries(TestCaseWithFactory, CopyCheckerHarness):
 
     def _setupSources(self, nb_of_sources):
         sources = []
-        for i in range(nb_of_sources):
+        for _ in range(nb_of_sources):
             source = self.test_publisher.getPubSource(
                 version="%d" % self.factory.getUniqueInteger(),
                 sourcename="name-%d" % self.factory.getUniqueInteger(),
diff --git a/lib/lp/soyuz/scripts/tests/test_custom_uploads_copier.py b/lib/lp/soyuz/scripts/tests/test_custom_uploads_copier.py
index 7d98ed4..8aed2a4 100644
--- a/lib/lp/soyuz/scripts/tests/test_custom_uploads_copier.py
+++ b/lib/lp/soyuz/scripts/tests/test_custom_uploads_copier.py
@@ -237,7 +237,7 @@ class TestCustomUploadsCopier(TestCaseWithFactory, CommonTestHelpers):
         # XXX JeroenVermeulen 2011-08-17, bug=827967: Should compare by
         # Debian version string, not id.
         source_series = self.factory.makeDistroSeries()
-        for counter in range(5):
+        for _ in range(5):
             self.makeUpload(source_series)
         copier = CustomUploadsCopier(FakeDistroSeries())
         candidate_ids = [
diff --git a/lib/lp/soyuz/tests/test_archive.py b/lib/lp/soyuz/tests/test_archive.py
index 5c17662..68134c5 100644
--- a/lib/lp/soyuz/tests/test_archive.py
+++ b/lib/lp/soyuz/tests/test_archive.py
@@ -153,7 +153,7 @@ class TestGetPublicationsInArchive(TestCaseWithFactory):
     def makeArchivesForOneDistribution(self, count=3):
         distribution = self.factory.makeDistribution()
         archives = []
-        for i in range(count):
+        for _ in range(count):
             archives.append(
                 self.factory.makeArchive(distribution=distribution)
             )
@@ -3854,7 +3854,7 @@ class TestGetPublishedSourcesWebService(TestCaseWithFactory):
         # 'addSource' to a `PackageUpload` ('launchpad.Edit'). It seems
         # too restrive to me.
         with person_logged_in(ppa.owner):
-            for i in range(5):
+            for _ in range(5):
                 upload = self.factory.makePackageUpload(
                     distroseries=distroseries, archive=ppa
                 )
diff --git a/lib/lp/soyuz/tests/test_distributionsourcepackagerelease.py b/lib/lp/soyuz/tests/test_distributionsourcepackagerelease.py
index 1140263..e4bacd3 100644
--- a/lib/lp/soyuz/tests/test_distributionsourcepackagerelease.py
+++ b/lib/lp/soyuz/tests/test_distributionsourcepackagerelease.py
@@ -148,7 +148,7 @@ class TestDistributionSourcePackageRelease(TestCaseWithFactory):
         self.assertThat(recorder, HasQueryCount(LessThan(5)))
         self.assertEqual(1, self.dsp_release.sample_binary_packages.count())
 
-        for iteration in range(5):
+        for _ in range(5):
             self.makeBinaryPackageRelease()
         self.updatePackageCache()
         with StormStatementRecorder() as recorder:
@@ -161,7 +161,7 @@ class TestDistributionSourcePackageRelease(TestCaseWithFactory):
         # DistributionSourcePackageRelease objects do not try to
         # retrieve DistroSeriesPackageCache records if they know
         # that such records do not exist.
-        for iteration in range(5):
+        for _ in range(5):
             self.makeBinaryPackageRelease()
         with StormStatementRecorder() as recorder:
             for ds_package in self.dsp_release.sample_binary_packages:
diff --git a/lib/lp/soyuz/tests/test_distroseriesdifferencejob.py b/lib/lp/soyuz/tests/test_distroseriesdifferencejob.py
index c6ce705..27ac653 100644
--- a/lib/lp/soyuz/tests/test_distroseriesdifferencejob.py
+++ b/lib/lp/soyuz/tests/test_distroseriesdifferencejob.py
@@ -163,7 +163,7 @@ class TestDistroSeriesDifferenceJobSource(TestCaseWithFactory):
 
     def createSPPHs(self, derived_series, nb_spph=10):
         res_spph = []
-        for i in range(nb_spph):
+        for _ in range(nb_spph):
             packagename = self.factory.makeSourcePackageName()
             spph = self.factory.makeSourcePackagePublishingHistory(
                 sourcepackagename=packagename,
@@ -455,7 +455,7 @@ class TestDistroSeriesDifferenceJobSource(TestCaseWithFactory):
         spn = spph.sourcepackagerelease.sourcepackagename
 
         create_jobs = list(range(1, 3))
-        for counter in create_jobs:
+        for _ in create_jobs:
             self.getJobSource().createForSPPHs([spph])
 
         job_count = len(
diff --git a/lib/lp/soyuz/tests/test_livefs.py b/lib/lp/soyuz/tests/test_livefs.py
index 7f98b2f..55578b0 100644
--- a/lib/lp/soyuz/tests/test_livefs.py
+++ b/lib/lp/soyuz/tests/test_livefs.py
@@ -624,7 +624,7 @@ class TestLiveFSSet(TestCaseWithFactory):
         owners = [self.factory.makePerson() for i in range(2)]
         livefses = []
         for owner in owners:
-            for i in range(2):
+            for _ in range(2):
                 livefses.append(
                     self.factory.makeLiveFS(registrant=owner, owner=owner)
                 )
diff --git a/lib/lp/soyuz/tests/test_livefsbuild.py b/lib/lp/soyuz/tests/test_livefsbuild.py
index f3b5cac..9b62712 100644
--- a/lib/lp/soyuz/tests/test_livefsbuild.py
+++ b/lib/lp/soyuz/tests/test_livefsbuild.py
@@ -284,7 +284,7 @@ class TestLiveFSBuild(TestCaseWithFactory):
             status=BuildStatus.FULLYBUILT,
             duration=timedelta(seconds=335),
         )
-        for i in range(3):
+        for _ in range(3):
             self.factory.makeLiveFSBuild(
                 requester=self.build.requester,
                 livefs=self.build.livefs,
diff --git a/lib/lp/soyuz/tests/test_packagecopyjob.py b/lib/lp/soyuz/tests/test_packagecopyjob.py
index 586c1b8..3716d63 100644
--- a/lib/lp/soyuz/tests/test_packagecopyjob.py
+++ b/lib/lp/soyuz/tests/test_packagecopyjob.py
@@ -640,7 +640,7 @@ class PlainPackageCopyJobTests(TestCaseWithFactory, LocalTestHelper):
     def test_iterReady_preempt(self):
         # Ordinary ("insecure") copy jobs that arrive in the middle of a
         # long mass-sync run take precedence immediately.
-        for i in range(2):
+        for _ in range(2):
             self.makeJob(copy_policy=PackageCopyPolicy.MASS_SYNC)
         iterator = getUtility(IPlainPackageCopyJobSource).iterReady()
         self.assertEqual(
diff --git a/lib/lp/soyuz/tests/test_processacceptedbugsjob.py b/lib/lp/soyuz/tests/test_processacceptedbugsjob.py
index 3716886..4a0e339 100644
--- a/lib/lp/soyuz/tests/test_processacceptedbugsjob.py
+++ b/lib/lp/soyuz/tests/test_processacceptedbugsjob.py
@@ -138,7 +138,7 @@ class TestClosingBugs(TestCaseWithFactory):
         # Make 4 bugs and corresponding bugtasks and put them in an array
         # as tuples.
         bugs = []
-        for i in range(6):
+        for _ in range(6):
             if target_series is None:
                 target_series = spr.upload_distroseries
             target = target_series.getSourcePackage(spr.sourcepackagename)
@@ -228,7 +228,7 @@ class TestClosingBugs(TestCaseWithFactory):
 
         close_bugs_for_sourcepublication(target_spph, since_version="1.0")
 
-        for bug, bugtask in bugs:
+        for _, bugtask in bugs:
             self.assertEqual(BugTaskStatus.FIXRELEASED, bugtask.status)
 
 
diff --git a/lib/lp/soyuz/tests/test_publishing.py b/lib/lp/soyuz/tests/test_publishing.py
index 20638b1..00ccd25 100644
--- a/lib/lp/soyuz/tests/test_publishing.py
+++ b/lib/lp/soyuz/tests/test_publishing.py
@@ -668,7 +668,7 @@ class SoyuzTestPublisher:
 
     def _findChangesFile(self, top, name_fragment):
         """File with given name fragment in directory tree starting at top."""
-        for root, dirs, files in os.walk(top, topdown=False):
+        for root, _, files in os.walk(top, topdown=False):
             for name in files:
                 if name.endswith(".changes") and name.find(name_fragment) > -1:
                     return os.path.join(root, name)
diff --git a/lib/lp/testing/__init__.py b/lib/lp/testing/__init__.py
index d8cbff9..a095111 100644
--- a/lib/lp/testing/__init__.py
+++ b/lib/lp/testing/__init__.py
@@ -436,7 +436,7 @@ def record_two_runs(
         recorder_factory = StormStatementRecorder
     if login_method is not None:
         login_method()
-    for i in range(first_round_number):
+    for _ in range(first_round_number):
         item_creator()
     # Record how many queries are issued when {tested_method} is
     # called after {item_creator} has been run {first_round_number}
@@ -452,7 +452,7 @@ def record_two_runs(
         second_round_number = first_round_number
     if login_method is not None:
         login_method()
-    for i in range(second_round_number):
+    for _ in range(second_round_number):
         item_creator()
     # Record again the number of queries issued.
     flush_database_caches()
@@ -1206,7 +1206,7 @@ def build_yui_unittest_suite(app_testing_path, yui_test_class):
 
 
 def _harvest_yui_test_files(file_path):
-    for dirpath, dirnames, filenames in os.walk(file_path):
+    for dirpath, _, filenames in os.walk(file_path):
         for filename in filenames:
             if fnmatchcase(filename, "test_*.html"):
                 yield os.path.join(dirpath, filename)
diff --git a/lib/lp/testing/dbuser.py b/lib/lp/testing/dbuser.py
index eeb2bdc..a6b6cef 100644
--- a/lib/lp/testing/dbuser.py
+++ b/lib/lp/testing/dbuser.py
@@ -29,7 +29,7 @@ def update_store_connections():
     underlying connection of *existing* stores, leaving existing objects
     functional.
     """
-    for name, store in getUtility(IZStorm).iterstores():
+    for _, store in getUtility(IZStorm).iterstores():
         connection = store._connection
         if connection._state == STATE_CONNECTED:
             if connection._raw_connection is not None:
diff --git a/lib/lp/testing/factory.py b/lib/lp/testing/factory.py
index 71fac63..bfc8744 100644
--- a/lib/lp/testing/factory.py
+++ b/lib/lp/testing/factory.py
@@ -1248,7 +1248,7 @@ class LaunchpadObjectFactory(ObjectFactory):
 
     def makeStackedOnBranchChain(self, depth=5, **kwargs):
         branch = None
-        for i in range(depth):
+        for _ in range(depth):
             branch = self.makeAnyBranch(stacked_on=branch, **kwargs)
         return branch
 
@@ -2011,7 +2011,7 @@ class LaunchpadObjectFactory(ObjectFactory):
         revision_set = getUtility(IRevisionSet)
         if author is None:
             author = self.getUniqueString("author")
-        for index in range(count):
+        for _ in range(count):
             revision = revision_set.new(
                 revision_id=self.getUniqueString("revision-id"),
                 log_body=self.getUniqueString("log-body"),
diff --git a/lib/lp/testing/fixture.py b/lib/lp/testing/fixture.py
index d5a7b74..0dd6145 100644
--- a/lib/lp/testing/fixture.py
+++ b/lib/lp/testing/fixture.py
@@ -123,7 +123,7 @@ class PGBouncerFixture(pgbouncer.fixture.PGBouncerFixture):
     def start(self, retries=20, sleep=0.5):
         """Start PGBouncer, waiting for it to accept connections."""
         super().start()
-        for i in range(retries):
+        for _ in range(retries):
             try:
                 socket.create_connection((self.host, self.port))
             except OSError:
diff --git a/lib/lp/testing/layers.py b/lib/lp/testing/layers.py
index cf94f50..637c47c 100644
--- a/lib/lp/testing/layers.py
+++ b/lib/lp/testing/layers.py
@@ -354,7 +354,7 @@ class BaseLayer:
         if BaseLayer.disable_thread_check:
             new_threads = None
         else:
-            for loop in range(0, 100):
+            for _ in range(0, 100):
                 # Check for tests that leave live threads around early.
                 # A live thread may be the cause of other failures, such as
                 # uncollectable garbage.
diff --git a/lib/lp/testing/swift/fakeswift.py b/lib/lp/testing/swift/fakeswift.py
index ef1378d..f466841 100644
--- a/lib/lp/testing/swift/fakeswift.py
+++ b/lib/lp/testing/swift/fakeswift.py
@@ -63,7 +63,7 @@ class FakeKeystone(resource.Resource):
             if token is not None and self._isValidToken(token, tenant_name):
                 return token
         else:
-            for id, token in self.tokens.items():
+            for _, token in self.tokens.items():
                 if self._isValidToken(token, tenant_name):
                     return token
 
diff --git a/lib/lp/testing/yuixhr.py b/lib/lp/testing/yuixhr.py
index bbc18cc..08bd097 100644
--- a/lib/lp/testing/yuixhr.py
+++ b/lib/lp/testing/yuixhr.py
@@ -451,7 +451,7 @@ class YUITestFixtureControllerView(LaunchpadView):
 
 
 def find_tests(root):
-    for dirpath, dirnames, filenames in os.walk(root):
+    for dirpath, _, filenames in os.walk(root):
         dirpath = os.path.relpath(dirpath, root)
         for filename in filenames:
             if fnmatchcase(filename, "test_*.js"):
diff --git a/lib/lp/tests/test_opensource.py b/lib/lp/tests/test_opensource.py
index d505809..ee84ed8 100644
--- a/lib/lp/tests/test_opensource.py
+++ b/lib/lp/tests/test_opensource.py
@@ -31,7 +31,7 @@ def add_testable_opensource_package(suite, package):
     topdir = os.path.dirname(package.__file__)
 
     packages = []
-    for dirpath, dirnames, filenames in os.walk(topdir):
+    for dirpath, dirnames, _ in os.walk(topdir):
         if "docs" in dirnames:
             docsdir = os.path.join(dirpath, "docs")[len(topdir) + 1 :]
             packages.append(docsdir)
diff --git a/lib/lp/translations/browser/tests/test_distroseries_views.py b/lib/lp/translations/browser/tests/test_distroseries_views.py
index 48c7bf0..0f818d5 100644
--- a/lib/lp/translations/browser/tests/test_distroseries_views.py
+++ b/lib/lp/translations/browser/tests/test_distroseries_views.py
@@ -75,7 +75,7 @@ class TestLanguagePacksView(TestCaseWithFactory):
         distroseries = self.factory.makeUbuntuDistroSeries()
         # This is one more than the default for shortlist.
         number_of_language_packs = 16
-        for i in range(number_of_language_packs):
+        for _ in range(number_of_language_packs):
             self.factory.makeLanguagePack(distroseries)
 
         view = create_initialized_view(
diff --git a/lib/lp/translations/browser/tests/test_translationimportqueueentry.py b/lib/lp/translations/browser/tests/test_translationimportqueueentry.py
index cc2a84b..9c44060 100644
--- a/lib/lp/translations/browser/tests/test_translationimportqueueentry.py
+++ b/lib/lp/translations/browser/tests/test_translationimportqueueentry.py
@@ -139,7 +139,7 @@ class TestTranslationImportQueueEntryView(WithScenarios, TestCaseWithFactory):
         # Many translatable series.  The list is cut short; there's an
         # ellipsis to indicate this.
         series_count = len(product.translatable_series)
-        for counter in range(series_count, view.max_series_to_display + 1):
+        for _ in range(series_count, view.max_series_to_display + 1):
             extra_series = self.factory.makeProductSeries(product=product)
             self.factory.makePOTemplate(productseries=extra_series)
         series_text = view.product_translatable_series
diff --git a/lib/lp/translations/model/currenttranslations.py b/lib/lp/translations/model/currenttranslations.py
index 84688a0..38d4cad 100644
--- a/lib/lp/translations/model/currenttranslations.py
+++ b/lib/lp/translations/model/currenttranslations.py
@@ -137,6 +137,6 @@ class CurrentTranslations:
         )
         for msgset in msgsets:
             cache = getattr(msgset, "_current_translations_cache", {})
-            for key, message in current_translations.items():
+            for key in current_translations:
                 cache[key] = current_translations[key]
             msgset._current_translations_cache = cache
diff --git a/lib/lp/translations/model/translationpolicy.py b/lib/lp/translations/model/translationpolicy.py
index f5b7248..be7e0aa 100644
--- a/lib/lp/translations/model/translationpolicy.py
+++ b/lib/lp/translations/model/translationpolicy.py
@@ -21,7 +21,7 @@ from lp.translations.model.translator import Translator
 
 def has_translators(translators_list):
     """Did `getTranslators` find any translators?"""
-    for group, translator, team in translators_list:
+    for _, _, team in translators_list:
         if team is not None:
             return True
     return False
@@ -29,7 +29,7 @@ def has_translators(translators_list):
 
 def is_in_one_of_translators(translators_list, person):
     """Is `person` a member of one of the entries in `getTranslators`?"""
-    for group, translator, team in translators_list:
+    for _, _, team in translators_list:
         if team is not None and person.inTeam(team):
             return True
     return False
diff --git a/lib/lp/translations/model/translationsoverview.py b/lib/lp/translations/model/translationsoverview.py
index a51ca0c..2852a76 100644
--- a/lib/lp/translations/model/translationsoverview.py
+++ b/lib/lp/translations/model/translationsoverview.py
@@ -89,7 +89,7 @@ class TranslationsOverview:
         # them to appropriate font size values.
         minimum = None
         maximum = None
-        for name, product_id, distro_id, relative_karma in cur.fetchall():
+        for _, product_id, distro_id, relative_karma in cur.fetchall():
             if minimum is None or relative_karma < minimum:
                 minimum = relative_karma
             if maximum is None or relative_karma > maximum:
diff --git a/lib/lp/translations/pottery/detect_intltool.py b/lib/lp/translations/pottery/detect_intltool.py
index 76a8a76..69ff368 100644
--- a/lib/lp/translations/pottery/detect_intltool.py
+++ b/lib/lp/translations/pottery/detect_intltool.py
@@ -28,7 +28,7 @@ def is_intltool_structure(tree):
     :returns: True if signs of an intltool structure were found.
     """
     with read_lock_tree(tree):
-        for thedir, files in tree.walkdirs():
+        for _, files in tree.walkdirs():
             for afile in files:
                 file_path, file_name, file_type = afile[:3]
                 if file_type != "file":
diff --git a/lib/lp/translations/tests/test_translationimportqueue.py b/lib/lp/translations/tests/test_translationimportqueue.py
index 8a51550..164046c 100644
--- a/lib/lp/translations/tests/test_translationimportqueue.py
+++ b/lib/lp/translations/tests/test_translationimportqueue.py
@@ -716,7 +716,7 @@ class TestHelpers(TestCaseWithFactory):
             for counter in range(2)
         ]
         for series in productseries:
-            for counter in range(2):
+            for _ in range(2):
                 self.factory.makeTranslationImportQueueEntry(
                     productseries=series
                 )
@@ -807,7 +807,7 @@ class TestHelpers(TestCaseWithFactory):
         self.useFixture(FakeLibrarian())
         series = self.factory.makeDistroSeries()
         series.defer_translation_imports = False
-        for counter in range(2):
+        for _ in range(2):
             self.factory.makeTranslationImportQueueEntry(distroseries=series)
         self.assertEqual([series], list_distroseries_request_targets(True))
 
diff --git a/lib/lp/translations/tests/test_translationsplitter.py b/lib/lp/translations/tests/test_translationsplitter.py
index 367a0f4..83e7d43 100644
--- a/lib/lp/translations/tests/test_translationsplitter.py
+++ b/lib/lp/translations/tests/test_translationsplitter.py
@@ -68,9 +68,10 @@ class TestTranslationSplitter(TestCaseWithFactory):
         splitter = make_translation_splitter(self.factory)
         make_shared_potmsgset(self.factory, splitter)
         make_shared_potmsgset(self.factory, splitter)
-        for num, (upstream, ubuntu) in enumerate(splitter.findShared()):
+        shared = list(splitter.findShared())
+        for upstream, ubuntu in shared:
             self.assertEqual(upstream.potmsgset, ubuntu.potmsgset)
-        self.assertEqual(1, num)
+        self.assertEqual(1, len(shared))
 
     def test_splitPOTMsgSet(self):
         """Splitting a POTMsgSet clones it and updates TemplateItem."""
diff --git a/lib/lp/translations/tests/test_translationtemplatesbuild.py b/lib/lp/translations/tests/test_translationtemplatesbuild.py
index e7196f2..aa09224 100644
--- a/lib/lp/translations/tests/test_translationtemplatesbuild.py
+++ b/lib/lp/translations/tests/test_translationtemplatesbuild.py
@@ -236,7 +236,7 @@ class TestTranslationTemplatesBuild(TestCaseWithFactory):
         source = getUtility(ITranslationTemplatesBuildSource)
         build_farm_jobs = []
         builds = []
-        for i in range(10):
+        for _ in range(10):
             branch = self.factory.makeBranch()
             build = source.create(branch)
             builds.append(build)
diff --git a/lib/lp/translations/utilities/gettext_po_parser.py b/lib/lp/translations/utilities/gettext_po_parser.py
index a383360..a67f416 100644
--- a/lib/lp/translations/utilities/gettext_po_parser.py
+++ b/lib/lp/translations/utilities/gettext_po_parser.py
@@ -701,7 +701,7 @@ class POParser:
                 # Octal escape.
                 position += 2
                 # Up to two more octal digits.
-                for i in range(2):
+                for _ in range(2):
                     if string[position].isdigit():
                         position += 1
                     else:
diff --git a/lib/lp/translations/utilities/tests/test_translation_importer.py b/lib/lp/translations/utilities/tests/test_translation_importer.py
index 98925ae..9c72920 100644
--- a/lib/lp/translations/utilities/tests/test_translation_importer.py
+++ b/lib/lp/translations/utilities/tests/test_translation_importer.py
@@ -98,7 +98,7 @@ class TranslationImporterTestCase(TestCaseWithFactory):
         exactly the same priority."""
         for file_extension in TranslationImporter().supported_file_extensions:
             priorities = []
-            for format, importer in importers.items():
+            for importer in importers.values():
                 if file_extension in importer.file_extensions:
                     self.assertNotIn(importer.priority, priorities)
                     priorities.append(importer.priority)
diff --git a/lib/lp/translations/utilities/xpi_header.py b/lib/lp/translations/utilities/xpi_header.py
index cfabddc..0e4ee58 100644
--- a/lib/lp/translations/utilities/xpi_header.py
+++ b/lib/lp/translations/utilities/xpi_header.py
@@ -70,7 +70,7 @@ class XpiHeader:
             parse = cElementTree.iterparse(
                 io.BytesIO(raw_content), forbid_dtd=True
             )
-            for event, elem in parse:
+            for _, elem in parse:
                 if elem.tag == contributor_tag:
                     # An XPI header can list multiple contributors, but
                     # here we care only about the latest one listed as a
diff --git a/scripts/librarian-report.py b/scripts/librarian-report.py
index 0281181..c1919a5 100755
--- a/scripts/librarian-report.py
+++ b/scripts/librarian-report.py
@@ -107,9 +107,7 @@ def main():
         total_bytes, formatted_size, num_files = cur.fetchone()
         totals.add((total_bytes, referring_table, formatted_size, num_files))
 
-    for total_bytes, tab_name, formatted_size, num_files in sorted(
-        totals, reverse=True
-    ):
+    for _, tab_name, formatted_size, num_files in sorted(totals, reverse=True):
         print("%-10s %s in %d files" % (formatted_size, tab_name, num_files))
 
     return 0
diff --git a/scripts/memcached-stats.py b/scripts/memcached-stats.py
index 73e0a2f..5f65226 100755
--- a/scripts/memcached-stats.py
+++ b/scripts/memcached-stats.py
@@ -33,7 +33,7 @@ INTERESTING_KEYS = [
 def get_summary(all_raw_stats):
     """Aggregate individual server statistics into a summary."""
     totals = {key: 0 for key in INTERESTING_KEYS}
-    for server, raw_stats in all_raw_stats:
+    for _, raw_stats in all_raw_stats:
         for key in INTERESTING_KEYS:
             totals[key] += int(raw_stats.get(key, 0))
     return totals
diff --git a/test_on_merge.py b/test_on_merge.py
index 8df3dc7..540a28c 100755
--- a/test_on_merge.py
+++ b/test_on_merge.py
@@ -67,7 +67,7 @@ def setup_test_database():
 
     # If there are existing database connections, terminate. We have
     # rogue processes still connected to the database.
-    for loop in range(2):
+    for _ in range(2):
         cur.execute(
             """
             SELECT usename, query
diff --git a/utilities/community-contributions.py b/utilities/community-contributions.py
index fe82b78..af4e378 100755
--- a/utilities/community-contributions.py
+++ b/utilities/community-contributions.py
@@ -536,7 +536,7 @@ class LogExCons(log.LogFormatter):
         # Go through the shallowest authored revisions and add their
         # top level revisions.
         for excon in self.all_ex_cons.values():
-            for rev, top_level_rev in excon.seen_revs.values():
+            for _, top_level_rev in excon.seen_revs.values():
                 excon.add_top_level_revision(top_level_rev)
 
         # Divide contributors into non-Canonical and Canonical.
diff --git a/utilities/generate-external-bug-status-docs b/utilities/generate-external-bug-status-docs
index cbe193e..e852747 100755
--- a/utilities/generate-external-bug-status-docs
+++ b/utilities/generate-external-bug-status-docs
@@ -31,7 +31,7 @@ from lp.bugs.externalbugtracker import BUG_TRACKER_CLASSES
 
 def generate_blank_lines(num):
     """Generate `num` blank lines."""
-    for i in range(num):
+    for _ in range(num):
         yield ""
 
 
diff --git a/utilities/pgmassacre.py b/utilities/pgmassacre.py
index 0939268..d809786 100755
--- a/utilities/pgmassacre.py
+++ b/utilities/pgmassacre.py
@@ -55,7 +55,7 @@ def rollback_prepared_transactions(database):
     )
     xids = [row[0] for row in cur.fetchall()]
     for xid in xids:
-        cur.execute("ROLLBACK PREPARED %(xid)s", vars())
+        cur.execute("ROLLBACK PREPARED %(xid)s", {"xid": xid})
     con.close()
 
 
diff --git a/utilities/pgstats.py b/utilities/pgstats.py
index d470605..eba3072 100755
--- a/utilities/pgstats.py
+++ b/utilities/pgstats.py
@@ -159,7 +159,7 @@ def main(dbname):
         print_row("Unused indexes", "N/A")
     else:
         print_row("Unused indexes", rows[0][1])
-        for table, index in rows[1:]:
+        for _, index in rows[1:]:
             print_row("", index)