← Back to team overview

launchpad-reviewers team mailing list archive

[Merge] ~cjwatson/launchpad:pyupgrade into launchpad:master

 

Colin Watson has proposed merging ~cjwatson/launchpad:pyupgrade into launchpad:master.

Commit message:
Apply pyupgrade

Requested reviews:
  Launchpad code reviewers (launchpad-reviewers)

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

I've started out with some conservative options that make minimal changes, so at the moment most of the changes are for things like using more modern set literal and dictionary comprehension syntax.  We can apply further options to upgrade to Python 3 syntax as a separate step.

`contrib` is excluded (as with `flake8`) because it consists of code mainly copied from elsewhere.

Except for the change to `.pre-commit-config.yaml`, all the changes here were automatic.  I've done a full test run with no errors.
-- 
Your team Launchpad code reviewers is requested to review the proposed merge of ~cjwatson/launchpad:pyupgrade into launchpad:master.
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 7c8290a..4042766 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -28,6 +28,12 @@ repos:
     hooks:
     -   id: flake8
         exclude: ^lib/contrib/
+-   repo: https://github.com/asottile/pyupgrade
+    rev: v2.29.1
+    hooks:
+    -   id: pyupgrade
+        args: [--keep-percent-format]
+        exclude: ^lib/contrib/
 -   repo: https://github.com/PyCQA/isort
     rev: 5.9.2
     hooks:
diff --git a/database/replication/helpers.py b/database/replication/helpers.py
index 726f1e6..b7e6bd4 100644
--- a/database/replication/helpers.py
+++ b/database/replication/helpers.py
@@ -78,7 +78,7 @@ LPMAIN_SEED = frozenset([
 # Explicitly list tables that should not be replicated. This includes the
 # session tables, as these might exist in developer databases but will not
 # exist in the production launchpad database.
-IGNORED_TABLES = set([
+IGNORED_TABLES = {
     # Session tables that in some situations will exist in the main lp
     # database.
     'public.secret', 'public.sessiondata', 'public.sessionpkgdata',
@@ -118,10 +118,10 @@ IGNORED_TABLES = set([
     'public.oauth_consumer_id_seq',
     'public.api_user_id_seq',
     'public.oauth_nonce_id_seq',
-    ])
+    }
 
 # Calculate IGNORED_SEQUENCES
-IGNORED_SEQUENCES = set('%s_id_seq' % table for table in IGNORED_TABLES)
+IGNORED_SEQUENCES = {'%s_id_seq' % table for table in IGNORED_TABLES}
 
 
 def slony_installed(con):
@@ -487,7 +487,7 @@ def calculate_replication_set(cur, seeds):
 
     # We can't easily convert the sequence name to (namespace, name) tuples,
     # so we might as well convert the tables to dot notation for consistancy.
-    tables = set(fqn(namespace, tablename) for namespace, tablename in tables)
+    tables = {fqn(namespace, tablename) for namespace, tablename in tables}
 
     return tables, sequences
 
@@ -503,24 +503,24 @@ def discover_unreplicated(cur):
 
     # Ignore any tables and sequences starting with temp_. These are
     # transient and not to be replicated per Bug #778338.
-    all_tables = set(
+    all_tables = {
         table for table in all_tables
-            if not table.startswith('public.temp_'))
-    all_sequences = set(
+            if not table.startswith('public.temp_')}
+    all_sequences = {
         sequence for sequence in all_sequences
-            if not sequence.startswith('public.temp_'))
+            if not sequence.startswith('public.temp_')}
 
     cur.execute("""
         SELECT tab_nspname, tab_relname FROM %s
         WHERE tab_nspname = 'public'
         """ % fqn(CLUSTER_NAMESPACE, "sl_table"))
-    replicated_tables = set(fqn(*row) for row in cur.fetchall())
+    replicated_tables = {fqn(*row) for row in cur.fetchall()}
 
     cur.execute("""
         SELECT seq_nspname, seq_relname FROM %s
         WHERE seq_nspname = 'public'
         """ % fqn(CLUSTER_NAMESPACE, "sl_sequence"))
-    replicated_sequences = set(fqn(*row) for row in cur.fetchall())
+    replicated_sequences = {fqn(*row) for row in cur.fetchall()}
 
     return (
         all_tables - replicated_tables - IGNORED_TABLES,
diff --git a/database/replication/walblock.py b/database/replication/walblock.py
index bcf48c4..49f1b61 100755
--- a/database/replication/walblock.py
+++ b/database/replication/walblock.py
@@ -39,7 +39,7 @@ def main():
             if options.verbose and not notified:
                 notified = True
                 print(
-                    'Blocking on {0} unshipped WAL'.format(
+                    'Blocking on {} unshipped WAL'.format(
                         len(glob(ready_wal_glob))),
                     end='', file=sys.stderr)
             time.sleep(5)
diff --git a/database/schema/preflight.py b/database/schema/preflight.py
index 9a8d8e5..24c5dfb 100755
--- a/database/schema/preflight.py
+++ b/database/schema/preflight.py
@@ -38,32 +38,32 @@ import upgrade
 
 
 # Ignore connections by these users.
-SYSTEM_USERS = set(['postgres', 'slony', 'nagios', 'lagmon'])
+SYSTEM_USERS = {'postgres', 'slony', 'nagios', 'lagmon'}
 
 # Fail checks if these users are connected. If a process should not be
 # interrupted by a rollout, the database user it connects as should be
 # added here. The preflight check will fail if any of these users are
 # connected, so these systems will need to be shut down manually before
 # a database update.
-FRAGILE_USERS = set([
+FRAGILE_USERS = {
     # process_accepted is fragile, but also fast so we likely shouldn't
     # need to ever manually shut it down.
     'process_accepted',
     'process_upload',
     'publish_distro',
     'publish_ftpmaster',
-    ])
+    }
 
 # If these users have long running transactions, just kill 'em. Entries
 # added here must come with a bug number, a if part of Launchpad holds
 # open a long running transaction it is a bug we need to fix.
-BAD_USERS = set([
+BAD_USERS = {
     'karma',  # Bug #863109
     'rosettaadmin',  # Bug #863122
     'update-pkg-cache',  # Bug #912144
     'process_death_row',  # Bug #912146
     'langpack',  # Bug #912147
-    ])
+    }
 
 # How lagged the cluster can be before failing the preflight check.
 # If this is set too low, perfectly normal state will abort rollouts. If
@@ -82,7 +82,7 @@ class DatabasePreflight:
 
         node = Node(None, None, None, True)
         node.con = master_con
-        self.nodes = set([node])
+        self.nodes = {node}
         self.lpmain_nodes = self.nodes
         self.lpmain_master_node = node
 
@@ -343,7 +343,7 @@ class KillConnectionsPreflight(DatabasePreflight):
         num_tries = 100
         seconds_to_pause = 0.1
         if self.replication_paused:
-            nodes = set([self.lpmain_master_node])
+            nodes = {self.lpmain_master_node}
         else:
             nodes = self.lpmain_nodes
 
diff --git a/database/schema/security.py b/database/schema/security.py
index 573486a..653a126 100755
--- a/database/schema/security.py
+++ b/database/schema/security.py
@@ -26,14 +26,14 @@ from lp.services.scripts import (
 # The 'read' group does not get given select permission on the following
 # tables. This is to stop the ro user being given access to security
 # sensitive information that interactive sessions don't need.
-SECURE_TABLES = set((
+SECURE_TABLES = {
     'public.oauthnonce',
     'public.oauthnonce_id_seq',
     'public.openidnonce',
     'public.openidnonce_id_seq',
     'public.openidconsumernonce',
     'public.openidconsumernonce_id_seq',
-    ))
+    }
 
 POSTGRES_ACL_MAP = {
     'r': 'SELECT',
@@ -218,9 +218,9 @@ class DbSchema(dict):
         options = (
             'SUPERUSER', 'INHERIT', 'CREATEROLE', 'CREATEDB', 'LOGIN',
             'REPLICATION')
-        self.roles = dict(
-            (r[0], set(opt for (opt, val) in zip(options, r[1:]) if val))
-            for r in cur.fetchall())
+        self.roles = {
+            r[0]: {opt for (opt, val) in zip(options, r[1:]) if val}
+            for r in cur.fetchall()}
 
 
 class CursorWrapper(object):
@@ -326,9 +326,9 @@ class PermissionGatherer:
 
     def countPrincipals(self):
         """Count the number of different principals."""
-        return len(set(sum([
+        return len(set(sum((
             list(principals)
-            for principals in six.itervalues(self.permissions)], [])))
+            for principals in six.itervalues(self.permissions)), [])))
 
     def grant(self, cur):
         """Grant all gathered permissions.
@@ -422,7 +422,7 @@ def reset_permissions(con, config, options):
         type_ = config.get(section_name, 'type')
         assert type_ in ['user', 'group'], 'Unknown type %s' % type_
 
-        desired_opts = set(('INHERIT',))
+        desired_opts = {'INHERIT'}
         if type_ == 'user':
             desired_opts.add('LOGIN')
 
@@ -476,7 +476,7 @@ def reset_permissions(con, config, options):
         else:
             log.debug2("%s not in any roles", user)
 
-    managed_roles = set(['read', 'admin'])
+    managed_roles = {'read', 'admin'}
     for section_name in config.sections():
         managed_roles.add(section_name)
         if section_name != 'public':
diff --git a/lib/devscripts/sourcecode.py b/lib/devscripts/sourcecode.py
index 2fa821e..2dd528a 100644
--- a/lib/devscripts/sourcecode.py
+++ b/lib/devscripts/sourcecode.py
@@ -128,7 +128,7 @@ def interpret_config(config_entries, public_only, use_http=False):
 
 def _subset_dict(d, keys):
     """Return a dict that's a subset of 'd', based on the keys in 'keys'."""
-    return dict((key, d[key]) for key in keys)
+    return {key: d[key] for key in keys}
 
 
 def plan_update(existing_branches, configuration):
diff --git a/lib/devscripts/tests/test_sourcecode.py b/lib/devscripts/tests/test_sourcecode.py
index e3abbf2..5d5f429 100644
--- a/lib/devscripts/tests/test_sourcecode.py
+++ b/lib/devscripts/tests/test_sourcecode.py
@@ -171,7 +171,7 @@ class TestPlanUpdate(unittest.TestCase):
         new, existing, removed = plan_update(['a', 'b', 'c'], {})
         self.assertEqual({}, new)
         self.assertEqual({}, existing)
-        self.assertEqual(set(['a', 'b', 'c']), removed)
+        self.assertEqual({'a', 'b', 'c'}, removed)
 
     def test_all_same(self):
         # If the set of existing branches is the same as the set of
diff --git a/lib/lp/answers/model/question.py b/lib/lp/answers/model/question.py
index 0441a70..61a534c 100644
--- a/lib/lp/answers/model/question.py
+++ b/lib/lp/answers/model/question.py
@@ -850,7 +850,7 @@ class QuestionSet:
     def getOpenQuestionCountByPackages(self, packages):
         """See `IQuestionSet`."""
         distributions = list(
-            set(package.distribution for package in packages))
+            {package.distribution for package in packages})
         # We can't get counts for all packages in one query, since we'd
         # need to match on (distribution, sourcepackagename). Issue one
         # query per distribution instead.
@@ -882,7 +882,7 @@ class QuestionSet:
         sourcepackagename_set = getUtility(ISourcePackageNameSet)
         # Only packages with open questions are included in the query
         # result, so initialize each package to 0.
-        counts = dict((package, 0) for package in packages)
+        counts = {package: 0 for package in packages}
         for distro_id, 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.
@@ -1525,6 +1525,6 @@ class QuestionTargetMixin:
         for contact in self.answer_contacts_with_languages:
             languages |= set(contact.languages)
         languages.add(getUtility(ILaunchpadCelebrities).english)
-        languages = set(
-            lang for lang in languages if not is_english_variant(lang))
+        languages = {
+            lang for lang in languages if not is_english_variant(lang)}
         return list(languages)
diff --git a/lib/lp/answers/model/tests/test_question.py b/lib/lp/answers/model/tests/test_question.py
index 0735fe3..979e2ce 100644
--- a/lib/lp/answers/model/tests/test_question.py
+++ b/lib/lp/answers/model/tests/test_question.py
@@ -99,7 +99,7 @@ class TestQuestionInDirectSubscribers(TestCaseWithFactory):
             english_person.addLanguage(getUtility(ILanguageSet)['en'])
         spanish = getUtility(ILanguageSet)['es']
         spanish_person = self.factory.makePerson()
-        with person_logged_in((spanish_person)):
+        with person_logged_in(spanish_person):
             spanish_person.addLanguage(spanish)
         question = self.factory.makeQuestion(language=spanish)
         with person_logged_in(question.owner):
diff --git a/lib/lp/answers/model/tests/test_questionsubscription.py b/lib/lp/answers/model/tests/test_questionsubscription.py
index 513914c..c20257b 100644
--- a/lib/lp/answers/model/tests/test_questionsubscription.py
+++ b/lib/lp/answers/model/tests/test_questionsubscription.py
@@ -126,7 +126,7 @@ class TestQuestionSubscriptionCanBeUnsubscribedbyUser(TestCaseWithFactory):
         """Question target answer contact can unsubscribe someone."""
         answer_contact = self.factory.makePerson()
         english = getUtility(ILanguageSet)['en']
-        with person_logged_in((answer_contact)):
+        with person_logged_in(answer_contact):
             answer_contact.addLanguage(english)
         distro_owner = self.factory.makePerson()
         distro = self.factory.makeDistribution(owner=distro_owner)
diff --git a/lib/lp/app/browser/launchpad.py b/lib/lp/app/browser/launchpad.py
index c9bb53e..6c5045f 100644
--- a/lib/lp/app/browser/launchpad.py
+++ b/lib/lp/app/browser/launchpad.py
@@ -188,9 +188,9 @@ class NavigationMenuTabs(LaunchpadView):
 
     def initialize(self):
         menuapi = MenuAPI(self.context)
-        self.links = sorted([
+        self.links = sorted((
             link for link in menuapi.navigation.values()
-            if (link.enabled or config.launchpad.devmode)],
+            if (link.enabled or config.launchpad.devmode)),
             key=operator.attrgetter('sort_key'))
         self.title = None
         if len(self.links) > 0:
@@ -273,9 +273,9 @@ class Hierarchy(LaunchpadView):
         """The objects for which we want breadcrumbs."""
         # Start the chain with the deepest object that has a breadcrumb.
         try:
-            objects = [next((
+            objects = [next(
                 obj for obj in reversed(self.request.traversed_objects)
-                if IBreadcrumb(obj, None)))]
+                if IBreadcrumb(obj, None))]
         except StopIteration:
             return []
         # Now iterate. If an object has a breadcrumb, it can override
diff --git a/lib/lp/app/browser/linkchecker.py b/lib/lp/app/browser/linkchecker.py
index b541907..fbdacc1 100644
--- a/lib/lp/app/browser/linkchecker.py
+++ b/lib/lp/app/browser/linkchecker.py
@@ -89,7 +89,7 @@ class LinkCheckerAPI(LaunchpadView):
         valid_links = {}
         user = self.user
         # List of all the bugs we are checking.
-        bugs_ids = set([int(link[len('/bugs/'):]) for link in links])
+        bugs_ids = {int(link[len('/bugs/'):]) for link in links}
         if bugs_ids:
             params = BugTaskSearchParams(
                 user=user, status=None,
diff --git a/lib/lp/app/browser/root.py b/lib/lp/app/browser/root.py
index fa6becd..f0e85f7 100644
--- a/lib/lp/app/browser/root.py
+++ b/lib/lp/app/browser/root.py
@@ -262,13 +262,13 @@ class LaunchpadSearchView(LaunchpadFormView):
     schema = ILaunchpadSearch
     field_names = ['text']
 
-    shipit_keywords = set([
+    shipit_keywords = {
         'ubuntu', 'kubuntu', 'edubuntu',
         'ship', 'shipit', 'send', 'get', 'mail', 'free',
-        'cd', 'cds', 'dvd', 'dvds', 'disc'])
-    shipit_anti_keywords = set([
+        'cd', 'cds', 'dvd', 'dvds', 'disc'}
+    shipit_anti_keywords = {
         'burn', 'burning', 'enable', 'error', 'errors', 'image', 'iso',
-        'read', 'rip', 'write'])
+        'read', 'rip', 'write'}
 
     def __init__(self, context, request):
         """Initialize the view.
diff --git a/lib/lp/app/browser/stringformatter.py b/lib/lp/app/browser/stringformatter.py
index bc40322..500ae96 100644
--- a/lib/lp/app/browser/stringformatter.py
+++ b/lib/lp/app/browser/stringformatter.py
@@ -243,7 +243,7 @@ def linkify_bug_numbers(text):
 def extract_email_addresses(text):
     '''Unique email addresses in the text.'''
     matches = re.finditer(re_email_address, text)
-    return list(set([match.group() for match in matches]))
+    return list({match.group() for match in matches})
 
 
 def parse_diff(text):
diff --git a/lib/lp/app/browser/tales.py b/lib/lp/app/browser/tales.py
index 51239bb..08d2a71 100644
--- a/lib/lp/app/browser/tales.py
+++ b/lib/lp/app/browser/tales.py
@@ -499,7 +499,7 @@ class NoneFormatter:
     attributes in content classes.
     """
 
-    allowed_names = set([
+    allowed_names = {
         'approximatedate',
         'approximatedatetitle',
         'approximateduration',
@@ -520,7 +520,7 @@ class NoneFormatter:
         'time',
         'url',
         'link',
-        ])
+        }
 
     def __init__(self, context):
         self.context = context
@@ -670,7 +670,7 @@ class ObjectFormatterAPI:
             "for %r." % (self, self._context))
 
     def global_css(self):
-        css_classes = set([])
+        css_classes = set()
         view = self._context
 
         # XXX: Bug #1076074
@@ -915,13 +915,13 @@ class BugTaskImageDisplayAPI(ObjectImageDisplayAPI):
     Used for image:icon.
     """
 
-    allowed_names = set([
+    allowed_names = {
         'icon',
         'logo',
         'mugshot',
         'badges',
         'sprite_css',
-        ])
+        }
 
     icon_template = (
         '<span alt="%s" title="%s" class="%s"></span>')
@@ -1424,9 +1424,9 @@ class CustomizableFormatter(ObjectFormatterAPI):
         This summary is for use in fmt:link, which is meant to be used in
         contexts like lists of items.
         """
-        values = dict(
-            (k, v if v is not None else '')
-            for k, v in six.iteritems(self._link_summary_values()))
+        values = {
+            k: v if v is not None else ''
+            for k, v in six.iteritems(self._link_summary_values())}
         return structured(self._link_summary_template, **values).escapedtext
 
     def _title_values(self):
@@ -1446,9 +1446,9 @@ class CustomizableFormatter(ObjectFormatterAPI):
         title_template = getattr(self, '_title_template', None)
         if title_template is None:
             return None
-        values = dict(
-            (k, v if v is not None else '')
-            for k, v in six.iteritems(self._title_values()))
+        values = {
+            k: v if v is not None else ''
+            for k, v in six.iteritems(self._title_values())}
         return structured(title_template, **values).escapedtext
 
     def sprite_css(self):
diff --git a/lib/lp/app/browser/tests/test_launchpad.py b/lib/lp/app/browser/tests/test_launchpad.py
index a25c46c..dc697fd 100644
--- a/lib/lp/app/browser/tests/test_launchpad.py
+++ b/lib/lp/app/browser/tests/test_launchpad.py
@@ -754,8 +754,8 @@ class TestIterViewRegistrations(TestCaseWithFactory):
         """iter_view_registrations provides only registrations of class."""
         macros = getMultiAdapter(
             (object(), LaunchpadTestRequest()), name='+base-layout-macros')
-        names = set(
-            reg.name for reg in iter_view_registrations(macros.__class__))
+        names = {
+            reg.name for reg in iter_view_registrations(macros.__class__)}
         self.assertIn('+base-layout-macros', names)
         self.assertNotIn('+related-pages', names)
 
diff --git a/lib/lp/app/tests/test_tales.py b/lib/lp/app/tests/test_tales.py
index 73a8464..ffd5f91 100644
--- a/lib/lp/app/tests/test_tales.py
+++ b/lib/lp/app/tests/test_tales.py
@@ -326,7 +326,7 @@ class TestNoneFormatterAPI(TestCaseWithFactory):
     def test_valid_traversal(self):
         # Traversal of allowed names works as expected.
 
-        allowed_names = set([
+        allowed_names = {
             'approximatedate',
             'approximateduration',
             'break-long-words',
@@ -345,7 +345,7 @@ class TestNoneFormatterAPI(TestCaseWithFactory):
             'time',
             'url',
             'link',
-            ])
+            }
 
         for name in allowed_names:
             self.assertEqual('', test_tales('foo/fmt:%s' % name, foo=None))
diff --git a/lib/lp/app/widgets/suggestion.py b/lib/lp/app/widgets/suggestion.py
index dc2a13e..6ce8e46 100644
--- a/lib/lp/app/widgets/suggestion.py
+++ b/lib/lp/app/widgets/suggestion.py
@@ -376,7 +376,7 @@ class RecipeOwnerWidget(SuggestionWidget):
     def _getSuggestions(branch):
         """Suggest the branch owner and current user."""
         logged_in_user = getUtility(ILaunchBag).user
-        return set([branch.owner, logged_in_user])
+        return {branch.owner, logged_in_user}
 
     @staticmethod
     def _valueDisplayname(value):
diff --git a/lib/lp/archivepublisher/model/ftparchive.py b/lib/lp/archivepublisher/model/ftparchive.py
index 2dcc94d..da2ecf6 100644
--- a/lib/lp/archivepublisher/model/ftparchive.py
+++ b/lib/lp/archivepublisher/model/ftparchive.py
@@ -198,10 +198,10 @@ class FTPArchiveHandler:
         spawner.complete()
         stdout_handler.finalize()
         stderr_handler.finalize()
-        failures = sorted([
+        failures = sorted(
             (tag, receiver.returncode)
             for tag, receiver in six.iteritems(returncodes)
-                if receiver.returncode != 0])
+                if receiver.returncode != 0)
         if len(failures) > 0:
             by_arch = ["%s (returned %d)" % failure for failure in failures]
             raise AptFTPArchiveFailure(
diff --git a/lib/lp/archivepublisher/publishing.py b/lib/lp/archivepublisher/publishing.py
index dec1312..a1f4ec0 100644
--- a/lib/lp/archivepublisher/publishing.py
+++ b/lib/lp/archivepublisher/publishing.py
@@ -143,7 +143,7 @@ def remove_suffix(path):
 
 def get_suffixed_indices(path):
     """Return a set of paths to compressed copies of the given index."""
-    return set([path + suffix for suffix in ('', '.gz', '.bz2', '.xz')])
+    return {path + suffix for suffix in ('', '.gz', '.bz2', '.xz')}
 
 
 def _getDiskPool(pubconf, log):
diff --git a/lib/lp/archivepublisher/scripts/publish_ftpmaster.py b/lib/lp/archivepublisher/scripts/publish_ftpmaster.py
index e691dfc..03bfe43 100644
--- a/lib/lp/archivepublisher/scripts/publish_ftpmaster.py
+++ b/lib/lp/archivepublisher/scripts/publish_ftpmaster.py
@@ -95,9 +95,9 @@ def map_distro_pubconfigs(distro):
     candidates = [
         (archive.purpose, getPubConfig(archive))
         for archive in get_publishable_archives(distro)]
-    return dict(
-        (purpose, config)
-        for purpose, config in candidates if config is not None)
+    return {
+        purpose: config
+        for purpose, config in candidates if config is not None}
 
 
 def newer_mtime(one_file, other_file):
@@ -185,9 +185,9 @@ class PublishFTPMaster(LaunchpadCronScript):
 
         So: getConfigs[distro][purpose] gives you a config.
         """
-        return dict(
-            (distro, map_distro_pubconfigs(distro))
-            for distro in self.distributions)
+        return {
+            distro: map_distro_pubconfigs(distro)
+            for distro in self.distributions}
 
     def locateIndexesMarker(self, distribution, suite):
         """Give path for marker file whose presence marks index creation.
@@ -266,9 +266,9 @@ class PublishFTPMaster(LaunchpadCronScript):
             only_unpublished=True))
         load_related(
             DistroArchSeries, pending_binaries, ['distroarchseriesID'])
-        return set(
+        return {
             pub.distroseries.name + pocketsuffix[pub.pocket]
-            for pub in pending_sources + pending_binaries)
+            for pub in pending_sources + pending_binaries}
 
     def getDirtySecuritySuites(self, distribution):
         """List security suites with pending publications."""
@@ -345,7 +345,7 @@ class PublishFTPMaster(LaunchpadCronScript):
         arguments = (
             ['-d', distribution.name] +
             args +
-            sum([['-s', suite] for suite in suites], []))
+            sum((['-s', suite] for suite in suites), []))
 
         publish_distro = PublishDistro(
             test_args=arguments, logger=self.logger, ignore_cron_control=True)
diff --git a/lib/lp/archivepublisher/tests/test_dominator.py b/lib/lp/archivepublisher/tests/test_dominator.py
index c079559..2b608fe 100755
--- a/lib/lp/archivepublisher/tests/test_dominator.py
+++ b/lib/lp/archivepublisher/tests/test_dominator.py
@@ -784,10 +784,10 @@ class TestDominatorMethods(TestCaseWithFactory):
         versions = ["1.%d" % number for number in range(4)]
 
         # We have one package releases for each version.
-        relevant_releases = dict(
-            (version, self.factory.makeSourcePackageRelease(
-                sourcepackagename=package, version=version))
-            for version in jumble(versions))
+        relevant_releases = {
+            version: self.factory.makeSourcePackageRelease(
+                sourcepackagename=package, version=version)
+            for version in jumble(versions)}
 
         # Each of those releases is subsequently published in
         # different components.
@@ -798,15 +798,15 @@ class TestDominatorMethods(TestCaseWithFactory):
         # oldest to newest.  Each re-publishing into a different
         # component is meant to supersede publication into the previous
         # component.
-        pubs_by_version = dict(
-            (version, [
+        pubs_by_version = {
+            version: [
                 self.factory.makeSourcePackagePublishingHistory(
                     archive=series.main_archive, distroseries=series,
                     pocket=pocket, status=PackagePublishingStatus.PUBLISHED,
                     sourcepackagerelease=relevant_releases[version],
                     component=component)
-                for component in components])
-            for version in jumble(versions))
+                for component in components]
+            for version in jumble(versions)}
 
         ages = jumble(
             [datetime.timedelta(age) for age in range(len(versions))])
@@ -904,11 +904,11 @@ class TestDominatorMethods(TestCaseWithFactory):
     def test_findPublishedSourcePackageNames_ignores_other_states(self):
         series = self.factory.makeDistroSeries()
         pocket = PackagePublishingPocket.RELEASE
-        spphs = dict(
-            (status, self.factory.makeSourcePackagePublishingHistory(
+        spphs = {
+            status: self.factory.makeSourcePackagePublishingHistory(
                 distroseries=series, archive=series.main_archive,
-                pocket=pocket, status=status))
-            for status in PackagePublishingStatus.items)
+                pocket=pocket, status=status)
+            for status in PackagePublishingStatus.items}
         published_spph = spphs[PackagePublishingStatus.PUBLISHED]
         dominator = self.makeDominator(list(spphs.values()))
         self.assertContentEqual(
@@ -988,13 +988,13 @@ class TestDominatorMethods(TestCaseWithFactory):
         series = self.factory.makeDistroSeries()
         package = self.factory.makeSourcePackageName()
         pocket = PackagePublishingPocket.RELEASE
-        spphs = dict(
-            (status, self.factory.makeSourcePackagePublishingHistory(
+        spphs = {
+            status: self.factory.makeSourcePackagePublishingHistory(
                 distroseries=series, archive=series.main_archive,
                 pocket=pocket, status=status,
                 sourcepackagerelease=self.factory.makeSourcePackageRelease(
-                    sourcepackagename=package)))
-            for status in PackagePublishingStatus.items)
+                    sourcepackagename=package))
+            for status in PackagePublishingStatus.items}
         dominator = self.makeDominator(list(spphs.values()))
         self.assertContentEqual(
             [spphs[PackagePublishingStatus.PUBLISHED]],
@@ -1336,7 +1336,7 @@ class TestArchSpecificPublicationsCache(TestCaseWithFactory):
         cache = self.makeCache()
         self.assertContentEqual(
             [cache.getKey(bpph) for bpph in bpphs],
-            set(cache.getKey(bpph) for bpph in bpphs * 2))
+            {cache.getKey(bpph) for bpph in bpphs * 2})
 
     def test_hasArchSpecificPublications_is_consistent_and_correct(self):
         # hasArchSpecificPublications consistently, repeatably returns
diff --git a/lib/lp/archivepublisher/tests/test_publish_ftpmaster.py b/lib/lp/archivepublisher/tests/test_publish_ftpmaster.py
index 8e01387..1847248 100644
--- a/lib/lp/archivepublisher/tests/test_publish_ftpmaster.py
+++ b/lib/lp/archivepublisher/tests/test_publish_ftpmaster.py
@@ -552,7 +552,7 @@ class TestPublishFTPMasterScript(
         script.runFinalizeParts(distro)
         _, kwargs = run_parts_fixture.new_value.calls[0]
         env = kwargs["env"]
-        required_parameters = set(["ARCHIVEROOTS", "SECURITY_UPLOAD_ONLY"])
+        required_parameters = {"ARCHIVEROOTS", "SECURITY_UPLOAD_ONLY"}
         missing_parameters = required_parameters.difference(set(env.keys()))
         self.assertEqual(set(), missing_parameters)
 
diff --git a/lib/lp/archivepublisher/tests/test_publisher.py b/lib/lp/archivepublisher/tests/test_publisher.py
index 977b626..176044a 100644
--- a/lib/lp/archivepublisher/tests/test_publisher.py
+++ b/lib/lp/archivepublisher/tests/test_publisher.py
@@ -2217,9 +2217,9 @@ class TestPublisher(TestPublisherBase):
 
         release = self.parseRelease(suite_path('Release'))
         paths = ['Release'] + [entry['name'] for entry in release['md5sum']]
-        timestamps = set(
+        timestamps = {
             os.stat(suite_path(path)).st_mtime for path in paths
-            if '/dep11/' not in path and os.path.exists(suite_path(path)))
+            if '/dep11/' not in path and os.path.exists(suite_path(path))}
         self.assertEqual(1, len(timestamps))
 
         # Non-core files preserve their original timestamps.
@@ -3380,8 +3380,8 @@ class TestPublisherLite(TestCaseWithFactory):
         paths = [path for path, _ in path_times]
         self.makePublisher(series)._syncTimestamps(series.name, set(paths))
 
-        timestamps = set(
-            os.stat(os.path.join(location, path)).st_mtime for path in paths)
+        timestamps = {
+            os.stat(os.path.join(location, path)).st_mtime for path in paths}
         self.assertEqual(1, len(timestamps))
         # The filesystem may round off subsecond parts of timestamps.
         self.assertEqual(int(now), int(list(timestamps)[0]))
diff --git a/lib/lp/archiveuploader/changesfile.py b/lib/lp/archiveuploader/changesfile.py
index 1a28b35..1a97999 100644
--- a/lib/lp/archiveuploader/changesfile.py
+++ b/lib/lp/archiveuploader/changesfile.py
@@ -58,13 +58,13 @@ class CannotDetermineFileTypeError(Exception):
 class ChangesFile(SignableTagFile):
     """Changesfile model."""
 
-    mandatory_fields = set([
+    mandatory_fields = {
         "Source", "Architecture", "Version", "Distribution",
         "Maintainer", "Files", "Changes", "Date",
         # Changed-By is not technically mandatory according to
         # Debian policy but Soyuz relies on it being set in
         # various places.
-        "Changed-By"])
+        "Changed-By"}
 
     # Map urgencies to their dbschema values.
     # Debian policy only permits low, medium, high, emergency.
diff --git a/lib/lp/archiveuploader/dscfile.py b/lib/lp/archiveuploader/dscfile.py
index 0ca6d03..50e6d70 100644
--- a/lib/lp/archiveuploader/dscfile.py
+++ b/lib/lp/archiveuploader/dscfile.py
@@ -250,15 +250,15 @@ class SignableTagFile:
 class DSCFile(SourceUploadFile, SignableTagFile):
     """Models a given DSC file and its content."""
 
-    mandatory_fields = set([
+    mandatory_fields = {
         "Source",
         "Version",
         "Binary",
         "Maintainer",
         "Architecture",
-        "Files"])
+        "Files"}
 
-    known_fields = mandatory_fields.union(set([
+    known_fields = mandatory_fields.union({
         "Build-Depends",
         "Build-Depends-Indep",
         "Build-Conflicts",
@@ -269,7 +269,7 @@ class DSCFile(SourceUploadFile, SignableTagFile):
         "Format",
         "Homepage",
         "Standards-Version",
-        ]))
+        })
 
     # Note that files is actually only set inside verify().
     files = None
diff --git a/lib/lp/archiveuploader/nascentupload.py b/lib/lp/archiveuploader/nascentupload.py
index eba9a06..cb6e144 100644
--- a/lib/lp/archiveuploader/nascentupload.py
+++ b/lib/lp/archiveuploader/nascentupload.py
@@ -458,7 +458,7 @@ class NascentUpload:
 
     def getComponents(self):
         """Return a set of components present in the uploaded files."""
-        return set(file.component_name for file in self.changes.files)
+        return {file.component_name for file in self.changes.files}
 
     def reject(self, msg):
         """Add the provided message to the rejection message."""
diff --git a/lib/lp/archiveuploader/nascentuploadfile.py b/lib/lp/archiveuploader/nascentuploadfile.py
index b3d68cc..e996fc4 100644
--- a/lib/lp/archiveuploader/nascentuploadfile.py
+++ b/lib/lp/archiveuploader/nascentuploadfile.py
@@ -215,7 +215,7 @@ class NascentUploadFile:
 
         # Read in the file and compute its md5 and sha1 checksums and remember
         # the size of the file as read-in.
-        digesters = dict((n, hashlib.new(n)) for n in self.checksums.keys())
+        digesters = {n: hashlib.new(n) for n in self.checksums.keys()}
         with open(self.filepath, "rb") as ckfile:
             size = 0
             for chunk in filechunks(ckfile):
@@ -432,9 +432,9 @@ class BaseBinaryUploadFile(PackageUploadFile):
     ddeb_file = None
 
     # Capitalised because we extract these directly from the control file.
-    mandatory_fields = set(["Package", "Architecture", "Version"])
+    mandatory_fields = {"Package", "Architecture", "Version"}
 
-    known_fields = mandatory_fields.union(set([
+    known_fields = mandatory_fields.union({
         "Depends",
         "Conflicts",
         "Breaks",
@@ -458,7 +458,7 @@ class BaseBinaryUploadFile(PackageUploadFile):
         "Maintainer",
         "Source",
         "Homepage",
-        ]))
+        })
 
     # Map priorities to their dbschema valuesa
     # We treat a priority of '-' as EXTRA since some packages in some distros
diff --git a/lib/lp/archiveuploader/tests/__init__.py b/lib/lp/archiveuploader/tests/__init__.py
index 6fe2757..2133cd0 100644
--- a/lib/lp/archiveuploader/tests/__init__.py
+++ b/lib/lp/archiveuploader/tests/__init__.py
@@ -49,7 +49,7 @@ def insertFakeChangesFile(fileID, path=None):
 
 def insertFakeChangesFileForAllPackageUploads():
     """Ensure all the PackageUpload records point to a valid changes file."""
-    for id in set(pu.changesfile.content.id for pu in PackageUploadSet()):
+    for id in {pu.changesfile.content.id for pu in PackageUploadSet()}:
         insertFakeChangesFile(id)
 
 
diff --git a/lib/lp/archiveuploader/tests/test_changesfile.py b/lib/lp/archiveuploader/tests/test_changesfile.py
index 6ce64e8..427b43b 100644
--- a/lib/lp/archiveuploader/tests/test_changesfile.py
+++ b/lib/lp/archiveuploader/tests/test_changesfile.py
@@ -209,7 +209,7 @@ class ChangesFileTests(TestCase):
         contents["Binary"] = "binary1\n binary2 \n binary3"
         changes = self.createChangesFile("mypkg_0.1_i386.changes", contents)
         self.assertEqual(
-            set(["binary1", "binary2", "binary3"]), changes.binaries)
+            {"binary1", "binary2", "binary3"}, changes.binaries)
 
     def test_checkFileName(self):
         # checkFileName() yields an UploadError if the filename is invalid.
@@ -245,7 +245,7 @@ class ChangesFileTests(TestCase):
         changes = self.createChangesFile(
             "mypkg_0.1_i386.changes", self.getBaseChanges())
         self.assertEqual("i386", changes.architecture_line)
-        self.assertEqual(set(["i386"]), changes.architectures)
+        self.assertEqual({"i386"}, changes.architectures)
 
     def test_source(self):
         # The source package name gets extracted from the changes file.
diff --git a/lib/lp/archiveuploader/utils.py b/lib/lp/archiveuploader/utils.py
index 949b37a..5ff24d2 100644
--- a/lib/lp/archiveuploader/utils.py
+++ b/lib/lp/archiveuploader/utils.py
@@ -324,7 +324,7 @@ def merge_file_lists(files, checksums_sha1, checksums_sha256, changes=True):
                 (filename, file_hashes[filename], size))
 
     # Ensure that each filename was only listed in Files once.
-    if set(six.itervalues(file_counter)) - set([1]):
+    if set(six.itervalues(file_counter)) - {1}:
         raise UploadError("Duplicate filenames in Files field.")
 
     # Ensure that the Checksums-Sha1 and Checksums-Sha256 fields, if
diff --git a/lib/lp/blueprints/browser/person_upcomingwork.py b/lib/lp/blueprints/browser/person_upcomingwork.py
index 5646a25..37b0030 100644
--- a/lib/lp/blueprints/browser/person_upcomingwork.py
+++ b/lib/lp/blueprints/browser/person_upcomingwork.py
@@ -62,7 +62,7 @@ class PersonUpcomingWorkView(LaunchpadView):
             if total_items > 0:
                 done_or_postponed = total_done + total_postponed
                 percent_done = 100.0 * done_or_postponed / total_items
-            self.progress_per_date[date] = '{0:.0f}'.format(percent_done)
+            self.progress_per_date[date] = '{:.0f}'.format(percent_done)
 
     @property
     def label(self):
@@ -124,7 +124,7 @@ class WorkItemContainer(object):
             done_or_postponed = (len(self.done_items) +
                                  len(self.postponed_items))
             percent_done = 100.0 * done_or_postponed / len(self._items)
-        return '{0:.0f}'.format(percent_done)
+        return '{:.0f}'.format(percent_done)
 
     @property
     def has_incomplete_work(self):
diff --git a/lib/lp/blueprints/browser/specification.py b/lib/lp/blueprints/browser/specification.py
index cc2d3b0..2f89e1e 100644
--- a/lib/lp/blueprints/browser/specification.py
+++ b/lib/lp/blueprints/browser/specification.py
@@ -1180,7 +1180,7 @@ class SpecGraph:
             graph.link(node, related)
         """
         # This is a standard pattern for "flattening" a recursive algorithm.
-        to_search = set([spec])
+        to_search = {spec}
         visited = set()
         while to_search:
             current_spec = to_search.pop()
@@ -1341,7 +1341,7 @@ class SpecGraphNode:
             # We want to have links in the image map for all nodes
             # except the one that were currently on the page of.
             attrnames.append('URL')
-        attrdict = dict((name, getattr(self, name)) for name in attrnames)
+        attrdict = {name: getattr(self, name) for name in attrnames}
         return u'%s\n%s' % (to_DOT_ID(self.name), dict_to_DOT_attrs(attrdict))
 
 
diff --git a/lib/lp/blueprints/browser/sprint.py b/lib/lp/blueprints/browser/sprint.py
index a7f1fdb..3945820 100644
--- a/lib/lp/blueprints/browser/sprint.py
+++ b/lib/lp/blueprints/browser/sprint.py
@@ -410,8 +410,8 @@ class SprintTopicSetView(HasSpecificationsView, LaunchpadView):
     def initialize(self):
         self.status_message = None
         self.process_form()
-        self.attendee_ids = set(
-            attendance.attendeeID for attendance in self.context.attendances)
+        self.attendee_ids = {
+            attendance.attendeeID for attendance in self.context.attendances}
 
     @cachedproperty
     def spec_filter(self):
@@ -523,8 +523,8 @@ class SprintMeetingExportView(LaunchpadView):
             if spec.drafter is not None:
                 spec_people[spec.drafter.id] = True
                 attendee_set.add(spec.drafter.id)
-        people_by_id = dict((person.id, person) for person in
-            getUtility(IPersonSet).getPrecachedPersonsFromIDs(attendee_set))
+        people_by_id = {person.id: person for person in
+            getUtility(IPersonSet).getPrecachedPersonsFromIDs(attendee_set)}
         self.specifications = [
             dict(spec=spec, interested=[
                     dict(name=people_by_id[person_id].name, required=required)
@@ -593,9 +593,9 @@ class SprintAttendeesCsvExportView(LaunchpadView):
             location = attendance.attendee.location
             if location is not None and location.visible:
                 time_zone = attendance.attendee.time_zone
-            irc_nicknames = ', '.join(sorted(set(
-                [ircid.nickname for ircid
-                 in attendance.attendee.ircnicknames])))
+            irc_nicknames = ', '.join(sorted({
+                ircid.nickname for ircid
+                 in attendance.attendee.ircnicknames}))
             rows.append(
                 (attendance.attendee.name,
                  attendance.attendee.displayname,
diff --git a/lib/lp/blueprints/browser/tests/test_specification.py b/lib/lp/blueprints/browser/tests/test_specification.py
index 19596ff..192f0c2 100644
--- a/lib/lp/blueprints/browser/tests/test_specification.py
+++ b/lib/lp/blueprints/browser/tests/test_specification.py
@@ -370,7 +370,7 @@ NEW_SPEC_FROM_ROOT_URL = 'http://blueprints.launchpad.test/specs/+new'
 
 class NewSpecificationTests:
 
-    expected_keys = set(['PROPRIETARY', 'PUBLIC', 'EMBARGOED'])
+    expected_keys = {'PROPRIETARY', 'PUBLIC', 'EMBARGOED'}
 
     def _create_form_data(self, context):
         return {
@@ -474,7 +474,7 @@ class TestNewSpecificationFromProductView(TestCaseWithFactory,
 
     layer = DatabaseFunctionalLayer
 
-    expected_keys = set(['PROPRIETARY', 'EMBARGOED'])
+    expected_keys = {'PROPRIETARY', 'EMBARGOED'}
 
     def createInitializedView(self):
         policy = SpecificationSharingPolicy.EMBARGOED_OR_PROPRIETARY
@@ -495,7 +495,7 @@ class TestNewSpecificationFromDistributionView(TestCaseWithFactory,
 
     layer = DatabaseFunctionalLayer
 
-    expected_keys = set(['PUBLIC'])
+    expected_keys = {'PUBLIC'}
 
     def createInitializedView(self):
         distro = self.factory.makeDistribution()
diff --git a/lib/lp/blueprints/browser/tests/test_specificationsubscription.py b/lib/lp/blueprints/browser/tests/test_specificationsubscription.py
index ab7ff1d..6f0d148 100644
--- a/lib/lp/blueprints/browser/tests/test_specificationsubscription.py
+++ b/lib/lp/blueprints/browser/tests/test_specificationsubscription.py
@@ -41,7 +41,7 @@ class TestSpecificationPortletSubcribersIds(TestCaseWithFactory):
             spec.subscribe(subscriber, subscriber)
             view = create_initialized_view(
                 spec, name="+blueprint-portlet-subscribers-ids")
-            subscriber_ids = dict(
-                    (subscriber.name, 'subscriber-%s' % subscriber.id)
-                    for subscriber in [person, subscriber])
+            subscriber_ids = {
+                    subscriber.name: 'subscriber-%s' % subscriber.id
+                    for subscriber in [person, subscriber]}
             self.assertEqual(subscriber_ids, view.subscriber_ids)
diff --git a/lib/lp/blueprints/model/specificationsearch.py b/lib/lp/blueprints/model/specificationsearch.py
index 0e77bc2..a8404ff 100644
--- a/lib/lp/blueprints/model/specificationsearch.py
+++ b/lib/lp/blueprints/model/specificationsearch.py
@@ -69,13 +69,13 @@ def search_specifications(context, base_clauses, user, sort=None,
     store = IStore(Specification)
     if not default_acceptance:
         default = SpecificationFilter.INCOMPLETE
-        options = set([
-            SpecificationFilter.COMPLETE, SpecificationFilter.INCOMPLETE])
+        options = {
+            SpecificationFilter.COMPLETE, SpecificationFilter.INCOMPLETE}
     else:
         default = SpecificationFilter.ACCEPTED
-        options = set([
+        options = {
             SpecificationFilter.ACCEPTED, SpecificationFilter.DECLINED,
-            SpecificationFilter.PROPOSED])
+            SpecificationFilter.PROPOSED}
     if not spec_filter:
         spec_filter = [default]
 
@@ -120,8 +120,8 @@ def search_specifications(context, base_clauses, user, sort=None,
             # If not specially looking for complete, we care about date
             # registered.
             order = []
-            show_proposed = set(
-                [SpecificationFilter.ALL, SpecificationFilter.PROPOSED])
+            show_proposed = {
+                SpecificationFilter.ALL, SpecificationFilter.PROPOSED}
             if default_acceptance and not (set(spec_filter) & show_proposed):
                 order.append(Desc(Specification.date_goal_decided))
             order.extend([Desc(Specification.datecreated), Specification.id])
@@ -135,8 +135,8 @@ def search_specifications(context, base_clauses, user, sort=None,
         work_items_by_spec = defaultdict(list)
         for spec in rows:
             if need_people:
-                person_ids |= set(
-                    [spec._assigneeID, spec._approverID, spec._drafterID])
+                person_ids |= {
+                    spec._assigneeID, spec._approverID, spec._drafterID}
             if need_branches:
                 get_property_cache(spec).linked_branches = []
         if need_workitems:
@@ -146,7 +146,7 @@ def search_specifications(context, base_clauses, user, sort=None,
             for workitem in work_items:
                 person_ids.add(workitem.assignee_id)
                 work_items_by_spec[workitem.specification_id].append(workitem)
-        person_ids -= set([None])
+        person_ids -= {None}
         if need_people:
             list(getUtility(IPersonSet).getPrecachedPersonsFromIDs(
                 person_ids, need_validity=True))
@@ -274,7 +274,7 @@ def _make_cache_user_can_view_spec(user):
     userid = user.id
 
     def cache_user_can_view_spec(spec):
-        get_property_cache(spec)._known_viewers = set([userid])
+        get_property_cache(spec)._known_viewers = {userid}
         return spec
     return cache_user_can_view_spec
 
diff --git a/lib/lp/blueprints/model/sprint.py b/lib/lp/blueprints/model/sprint.py
index 65c04b8..32607bb 100644
--- a/lib/lp/blueprints/model/sprint.py
+++ b/lib/lp/blueprints/model/sprint.py
@@ -192,7 +192,7 @@ class Sprint(StormBase, HasDriversMixin, HasSpecificationsMixin):
         # need_* is provided only for interface compatibility and
         # need_*=True is not implemented.
         if filter is None:
-            filter = set([SpecificationFilter.ACCEPTED])
+            filter = {SpecificationFilter.ACCEPTED}
         tables, query = self.spec_filter_clause(user, filter)
         # import here to avoid circular deps
         from lp.blueprints.model.specification import Specification
diff --git a/lib/lp/blueprints/tests/test_specification.py b/lib/lp/blueprints/tests/test_specification.py
index 3ce41fe..68198a6 100644
--- a/lib/lp/blueprints/tests/test_specification.py
+++ b/lib/lp/blueprints/tests/test_specification.py
@@ -158,9 +158,9 @@ class SpecificationTests(TestCaseWithFactory):
 
     def test_get_permissions(self):
         expected_get_permissions = {
-            CheckerPublic: set((
-                'id', 'information_type', 'private', 'userCanView')),
-            'launchpad.LimitedView': set((
+            CheckerPublic: {
+                'id', 'information_type', 'private', 'userCanView'},
+            'launchpad.LimitedView': {
                 'all_blocked', 'all_deps', 'approver', 'approverID',
                 'assignee', 'assigneeID', 'bugs', 'completer',
                 'createDependency', 'date_completed', 'date_goal_decided',
@@ -182,14 +182,14 @@ class SpecificationTests(TestCaseWithFactory):
                 'superseded_by', 'target', 'title', 'unlinkBranch',
                 'unlinkSprint', 'unsubscribe', 'updateLifecycleStatus',
                 'validateMove', 'whiteboard', 'work_items',
-                'workitems_text')),
-            'launchpad.Edit': set((
+                'workitems_text'},
+            'launchpad.Edit': {
                 'newWorkItem', 'proposeGoal', 'retarget',
                 'setDefinitionStatus', 'setImplementationStatus', 'setTarget',
-                'transitionToInformationType', 'updateWorkItems')),
-            'launchpad.Driver': set(('acceptBy', 'declineBy')),
-            'launchpad.AnyLegitimatePerson': set((
-                'unlinkBug', 'linkBug', 'setWorkItems')),
+                'transitionToInformationType', 'updateWorkItems'},
+            'launchpad.Driver': {'acceptBy', 'declineBy'},
+            'launchpad.AnyLegitimatePerson': {
+                'unlinkBug', 'linkBug', 'setWorkItems'},
             }
         specification = self.factory.makeSpecification()
         checker = getChecker(specification)
@@ -198,13 +198,13 @@ class SpecificationTests(TestCaseWithFactory):
 
     def test_set_permissions(self):
         expected_get_permissions = {
-            'launchpad.Admin': set(('direction_approved', 'priority')),
-            'launchpad.AnyLegitimatePerson': set(('whiteboard', )),
-            'launchpad.Edit': set((
+            'launchpad.Admin': {'direction_approved', 'priority'},
+            'launchpad.AnyLegitimatePerson': {'whiteboard'},
+            'launchpad.Edit': {
                 'approver', 'assignee', 'definition_status', 'distribution',
                 'drafter', 'implementation_status', 'man_days', 'milestone',
                 'name', 'product', 'specurl', 'summary', 'superseded_by',
-                'title')),
+                'title'},
             }
         specification = self.factory.makeSpecification()
         checker = getChecker(specification)
diff --git a/lib/lp/bugs/browser/bug.py b/lib/lp/bugs/browser/bug.py
index 04c4f69..f4e5eea 100644
--- a/lib/lp/bugs/browser/bug.py
+++ b/lib/lp/bugs/browser/bug.py
@@ -570,10 +570,10 @@ class BugView(LaunchpadView, BugViewMixin):
         """
         duplicate_bugs = list(self.context.duplicates)
         current_task = self.current_bugtask
-        dupes_in_current_context = dict(
-            (bugtask.bug, bugtask)
+        dupes_in_current_context = {
+            bugtask.bug: bugtask
             for bugtask in current_task.target.searchTasks(
-                BugTaskSearchParams(self.user, bug=any(*duplicate_bugs))))
+                BugTaskSearchParams(self.user, bug=any(*duplicate_bugs)))}
         dupes = []
         for bug in duplicate_bugs:
             # Don't disclose even the ID of a private bug. The link will
diff --git a/lib/lp/bugs/browser/bugalsoaffects.py b/lib/lp/bugs/browser/bugalsoaffects.py
index d1bfe3e..40f30f4 100644
--- a/lib/lp/bugs/browser/bugalsoaffects.py
+++ b/lib/lp/bugs/browser/bugalsoaffects.py
@@ -650,8 +650,8 @@ class ProductBugTaskCreationStep(BugTaskCreationStep):
         # link_upstream_how has _displayItemForMissingValue=False
         # so that renderItems() doesn't return an extra radio button which
         # prevents it from matching widget.vocabulary's ordering.
-        return dict((entry.token, items[i])
-                    for i, entry in enumerate(widget.vocabulary))
+        return {entry.token: items[i]
+                    for i, entry in enumerate(widget.vocabulary)}
 
     def main_action(self, data):
         link_upstream_how = data.get('link_upstream_how')
diff --git a/lib/lp/bugs/browser/buglisting.py b/lib/lp/bugs/browser/buglisting.py
index 8e8e49e..3a4a6c3 100644
--- a/lib/lp/bugs/browser/buglisting.py
+++ b/lib/lp/bugs/browser/buglisting.py
@@ -1070,8 +1070,8 @@ class BugTaskSearchListingView(LaunchpadFormView, FeedsMixin, BugsInfoMixin):
             not FeedsLayer.providedBy(self.request) and
             not self.request.form.get('advanced')):
             cache = IJSONRequestCache(self.request)
-            view_names = set(reg.name for reg
-                in iter_view_registrations(self.__class__))
+            view_names = {reg.name for reg
+                in iter_view_registrations(self.__class__)}
             if len(view_names) != 1:
                 raise AssertionError("Ambiguous view name.")
             cache.objects['view_name'] = view_names.pop()
@@ -1157,7 +1157,7 @@ class BugTaskSearchListingView(LaunchpadFormView, FeedsMixin, BugsInfoMixin):
                     "are out of date or you changed the URL by hand?" %
                     field_name)
 
-        sort_column_names = set(sort_key[0] for sort_key in SORT_KEYS)
+        sort_column_names = {sort_key[0] for sort_key in SORT_KEYS}
         orderby = get_sortorder_from_request(self.request)
         for orderby_col in orderby:
             if orderby_col.startswith("-"):
diff --git a/lib/lp/bugs/browser/bugtarget.py b/lib/lp/bugs/browser/bugtarget.py
index a8bfe2e..d140bca 100644
--- a/lib/lp/bugs/browser/bugtarget.py
+++ b/lib/lp/bugs/browser/bugtarget.py
@@ -1222,12 +1222,12 @@ class BugTargetBugTagsView(LaunchpadView):
             self.user, 10, official_tags)
 
         return sorted(
-            [dict(
+            (dict(
                 tag=tag,
                 count=count,
                 url=self._getSearchURL(tag),
                 )
-            for (tag, count) in six.iteritems(tags)],
+            for (tag, count) in six.iteritems(tags)),
             key=lambda item: (-item['count'], item['tag']))
 
     @property
diff --git a/lib/lp/bugs/browser/bugtask.py b/lib/lp/bugs/browser/bugtask.py
index 5852a49..a4b0fc0 100644
--- a/lib/lp/bugs/browser/bugtask.py
+++ b/lib/lp/bugs/browser/bugtask.py
@@ -284,7 +284,7 @@ def get_visible_comments(comments, user=None):
     # so that checking owner.is_valid_person, when rendering the link,
     # won't issue a DB query. Note that this should be obsolete now with
     # getMessagesForView improvements.
-    commenters = set(comment.owner for comment in visible_comments)
+    commenters = {comment.owner for comment in visible_comments}
     getUtility(IPersonSet).getValidPersons(commenters)
 
     # If a user is supplied, we can also strip out comments that the user
@@ -602,8 +602,8 @@ class BugTaskView(LaunchpadView, BugViewMixin, FeedsMixin):
             activity_item for activity_item in activity
             if interesting_match(activity_item.whatchanged) is not None]
         # Pre-load the doers of the activities in one query.
-        person_ids = set(
-            activity_item.personID for activity_item in activity_items)
+        person_ids = {
+            activity_item.personID for activity_item in activity_items}
         list(getUtility(IPersonSet).getPrecachedPersonsFromIDs(
             person_ids, need_validity=True))
 
@@ -703,10 +703,10 @@ class BugTaskView(LaunchpadView, BugViewMixin, FeedsMixin):
                     activities, attrgetter("target"))]
 
         def comment_event_dict(comment):
-            actors = set(activity.person for activity in comment.activity)
+            actors = {activity.person for activity in comment.activity}
             actors.add(comment.owner)
             assert len(actors) == 1, actors
-            dates = set(activity.datechanged for activity in comment.activity)
+            dates = {activity.datechanged for activity in comment.activity}
             dates.add(comment.datecreated)
             comment.activity = group_activities_by_target(comment.activity)
             return {
@@ -716,9 +716,9 @@ class BugTaskView(LaunchpadView, BugViewMixin, FeedsMixin):
                 }
 
         def activity_event_dict(activities):
-            actors = set(activity.person for activity in activities)
+            actors = {activity.person for activity in activities}
             assert len(actors) == 1, actors
-            dates = set(activity.datechanged for activity in activities)
+            dates = {activity.datechanged for activity in activities}
             return {
                 "activity": group_activities_by_target(activities),
                 "date": min(dates),
@@ -1173,7 +1173,7 @@ class BugTaskEditView(LaunchpadEditFormView, BugTaskBugWatchMixin,
                 if 'importance' in editable_field_names:
                     editable_field_names.remove("importance")
         else:
-            editable_field_names = set(('bugwatch', ))
+            editable_field_names = {'bugwatch'}
             if self.context.bugwatch is None:
                 editable_field_names.update(('status', 'assignee'))
                 if ('importance' in self.default_field_names
@@ -1250,8 +1250,8 @@ class BugTaskEditView(LaunchpadEditFormView, BugTaskBugWatchMixin,
             if self.user is None:
                 status_noshow = set(BugTaskStatus.items)
             else:
-                status_noshow = set((
-                    BugTaskStatus.UNKNOWN, BugTaskStatus.EXPIRED))
+                status_noshow = {
+                    BugTaskStatus.UNKNOWN, BugTaskStatus.EXPIRED}
                 status_noshow.update(
                     status for status in BugTaskStatus.items
                     if not self.context.canTransitionToStatus(
diff --git a/lib/lp/bugs/browser/bugtracker.py b/lib/lp/bugs/browser/bugtracker.py
index 95c1479..dee3683 100644
--- a/lib/lp/bugs/browser/bugtracker.py
+++ b/lib/lp/bugs/browser/bugtracker.py
@@ -375,9 +375,9 @@ class BugTrackerEditView(LaunchpadEditFormView):
 
         # If the bugtracker is a celebrity then we protect it from
         # deletion.
-        celebrities_set = set(
+        celebrities_set = {
             getattr(celebrities, name)
-            for name in ILaunchpadCelebrities.names())
+            for name in ILaunchpadCelebrities.names()}
         if self.context in celebrities_set:
             reasons.append(
                 'This bug tracker is protected from deletion.')
diff --git a/lib/lp/bugs/browser/structuralsubscription.py b/lib/lp/bugs/browser/structuralsubscription.py
index 66415f3..5506bee 100644
--- a/lib/lp/bugs/browser/structuralsubscription.py
+++ b/lib/lp/bugs/browser/structuralsubscription.py
@@ -155,10 +155,10 @@ class StructuralSubscriptionView(LaunchpadFormView):
         be removed, else return None.
         """
         teams = set(self.user_teams)
-        other_subscriptions = set(
+        other_subscriptions = {
             subscription.subscriber
             for subscription
-            in self.context.bug_subscriptions)
+            in self.context.bug_subscriptions}
 
         # Teams and the current user have their own UI elements. Remove
         # them to avoid duplicates.
@@ -196,9 +196,9 @@ class StructuralSubscriptionView(LaunchpadFormView):
     def initial_values(self):
         """See `LaunchpadFormView`."""
         teams = set(self.user_teams)
-        subscribed_teams = set(team
+        subscribed_teams = {team
                                for team in teams
-                               if self.isSubscribed(team))
+                               if self.isSubscribed(team)}
         return {
             'subscribe_me': self.currentUserIsSubscribed(),
             'subscriptions_team': subscribed_teams,
@@ -261,8 +261,8 @@ class StructuralSubscriptionView(LaunchpadFormView):
         target = self.context
         teams = set(self.user_teams)
         form_selected_teams = teams & set(form_selected_teams)
-        subscriptions = set(
-            team for team in teams if self.isSubscribed(team))
+        subscriptions = {
+            team for team in teams if self.isSubscribed(team)}
 
         for team in form_selected_teams - subscriptions:
             target.addBugSubscription(team, self.user)
diff --git a/lib/lp/bugs/browser/tests/test_bugcomment.py b/lib/lp/bugs/browser/tests/test_bugcomment.py
index c23f3b0..f93a5c9 100644
--- a/lib/lp/bugs/browser/tests/test_bugcomment.py
+++ b/lib/lp/bugs/browser/tests/test_bugcomment.py
@@ -129,7 +129,7 @@ class TestGroupCommentsWithActivities(TestCase):
         activity2 = BugActivityStub(next(self.time_index)[0])
         comment2 = BugCommentStub(*next(self.time_index))
 
-        activities = set([activity1, activity2])
+        activities = {activity1, activity2}
         comments = list([comment1, comment2])
 
         self.assertEqual(
diff --git a/lib/lp/bugs/browser/tests/test_bugsubscriptionfilter.py b/lib/lp/bugs/browser/tests/test_bugsubscriptionfilter.py
index c0db2c2..342e984 100644
--- a/lib/lp/bugs/browser/tests/test_bugsubscriptionfilter.py
+++ b/lib/lp/bugs/browser/tests/test_bugsubscriptionfilter.py
@@ -160,7 +160,7 @@ class TestBugSubscriptionFilterAPIModifications(
         self.assertTrue(self.subscription_filter.include_any_tags)
         self.assertTrue(self.subscription_filter.exclude_any_tags)
         self.assertEqual(
-            set(["*", "-*", "foo", "-bar"]),
+            {"*", "-*", "foo", "-bar"},
             self.subscription_filter.tags)
 
     def test_modify_description(self):
@@ -189,7 +189,7 @@ class TestBugSubscriptionFilterAPIModifications(
 
         # Updated state.
         self.assertEqual(
-            set([BugTaskStatus.NEW, BugTaskStatus.TRIAGED]),
+            {BugTaskStatus.NEW, BugTaskStatus.TRIAGED},
             self.subscription_filter.statuses)
 
     def test_modify_importances(self):
@@ -204,7 +204,7 @@ class TestBugSubscriptionFilterAPIModifications(
 
         # Updated state.
         self.assertEqual(
-            set([BugTaskImportance.LOW, BugTaskImportance.HIGH]),
+            {BugTaskImportance.LOW, BugTaskImportance.HIGH},
             self.subscription_filter.importances)
 
     def test_delete(self):
diff --git a/lib/lp/bugs/browser/tests/test_bugtask.py b/lib/lp/bugs/browser/tests/test_bugtask.py
index 4cc1c9c..5eb97d6 100644
--- a/lib/lp/bugs/browser/tests/test_bugtask.py
+++ b/lib/lp/bugs/browser/tests/test_bugtask.py
@@ -2491,7 +2491,7 @@ class TestBugTaskSearchListingView(BrowserTestCase):
         view = self.makeView()
         cache = IJSONRequestCache(view.request)
         json_sort_keys = cache.objects['sort_keys']
-        json_sort_keys = set(key[0] for key in json_sort_keys)
+        json_sort_keys = {key[0] for key in json_sort_keys}
         valid_keys = set(orderby_expression.keys())
         self.assertEqual(
             valid_keys, json_sort_keys,
diff --git a/lib/lp/bugs/externalbugtracker/bugzilla.py b/lib/lp/bugs/externalbugtracker/bugzilla.py
index 7a84697..a84a575 100644
--- a/lib/lp/bugs/externalbugtracker/bugzilla.py
+++ b/lib/lp/bugs/externalbugtracker/bugzilla.py
@@ -845,8 +845,8 @@ class BugzillaAPI(Bugzilla):
                 del comments[comment_id]
 
         # Ensure that comment IDs are converted to ints.
-        comments_with_int_ids = dict(
-            (int(id), comments[id]) for id in comments)
+        comments_with_int_ids = {
+            int(id): comments[id] for id in comments}
         self._bugs[actual_bug_id]['comments'] = comments_with_int_ids
 
     def getPosterForComment(self, remote_bug_id, comment_id):
@@ -1090,8 +1090,8 @@ class BugzillaLPPlugin(BugzillaAPI):
         comment_list = bug_comments_dict['bugs'][str(actual_bug_id)]
 
         # Transfer the comment list into a dict.
-        bug_comments = dict(
-            (comment['id'], comment) for comment in comment_list)
+        bug_comments = {
+            comment['id']: comment for comment in comment_list}
 
         self._bugs[actual_bug_id]['comments'] = bug_comments
 
diff --git a/lib/lp/bugs/interfaces/bugtasksearch.py b/lib/lp/bugs/interfaces/bugtasksearch.py
index ce3970a..7c18d58 100644
--- a/lib/lp/bugs/interfaces/bugtasksearch.py
+++ b/lib/lp/bugs/interfaces/bugtasksearch.py
@@ -217,7 +217,7 @@ class BugTaskSearchParams:
         if isinstance(information_type, collections.Iterable):
             self.information_type = set(information_type)
         elif information_type:
-            self.information_type = set((information_type,))
+            self.information_type = {information_type}
         else:
             self.information_type = None
         self.ignore_privacy = ignore_privacy
@@ -674,7 +674,7 @@ def get_person_bugtasks_search_params(user, context, **kwargs):
         # modified the query in an invalid way by overwriting all user
         # related parameters
         raise IllegalRelatedBugTasksParams(
-            ('Cannot search for related tasks to \'%s\', at least one '
+            'Cannot search for related tasks to \'%s\', at least one '
              'of these parameter has to be empty: %s'
-                % (context.name, ", ".join(relevant_fields))))
+                % (context.name, ", ".join(relevant_fields)))
     return search_params
diff --git a/lib/lp/bugs/interfaces/tests/test_bugtask.py b/lib/lp/bugs/interfaces/tests/test_bugtask.py
index 3c33527..f940c15 100644
--- a/lib/lp/bugs/interfaces/tests/test_bugtask.py
+++ b/lib/lp/bugs/interfaces/tests/test_bugtask.py
@@ -17,9 +17,9 @@ class TestFunctions(TestCase):
 
     def test_get_bugtask_status(self):
         # Compose a map of BugTaskStatusSearch members from their values.
-        expected = dict(
-            (status.value, status)
-            for status in BugTaskStatusSearch.items)
+        expected = {
+            status.value: status
+            for status in BugTaskStatusSearch.items}
         # Update the expected status map - overwriting some entries - from
         # BugTaskStatus members and their values.
         expected.update(
@@ -27,9 +27,9 @@ class TestFunctions(TestCase):
             for status in BugTaskStatus.items)
         # Compose a map of statuses as discovered by value for each member of
         # BugTaskStatusSearch.
-        observed = dict(
-            (status.value, get_bugtask_status(status.value))
-            for status in BugTaskStatusSearch.items)
+        observed = {
+            status.value: get_bugtask_status(status.value)
+            for status in BugTaskStatusSearch.items}
         # Update the expected status map with statuses discovered by value for
         # each member of BugTaskStatus.
         observed.update(
@@ -52,9 +52,9 @@ class TestFunctions(TestCase):
             BugTaskStatus.UNKNOWN: BugTaskStatus.UNKNOWN,
             BugTaskStatus.WONTFIX: BugTaskStatus.WONTFIX,
             }
-        observed = dict(
-            (status, normalize_bugtask_status(status))
-            for status in BugTaskStatus.items)
+        observed = {
+            status: normalize_bugtask_status(status)
+            for status in BugTaskStatus.items}
         self.assertEqual(expected, observed)
 
     def test_normalize_bugtask_status_from_BugTaskStatusSearch(self):
@@ -75,9 +75,9 @@ class TestFunctions(TestCase):
             BugTaskStatusSearch.TRIAGED: BugTaskStatus.TRIAGED,
             BugTaskStatusSearch.WONTFIX: BugTaskStatus.WONTFIX,
             }
-        observed = dict(
-            (status, normalize_bugtask_status(status))
-            for status in BugTaskStatusSearch.items)
+        observed = {
+            status: normalize_bugtask_status(status)
+            for status in BugTaskStatusSearch.items}
         self.assertEqual(expected, observed)
 
     def test_normalize_bugtask_status_from_BugTaskStatusSearchDisplay(self):
@@ -99,7 +99,7 @@ class TestFunctions(TestCase):
             BugTaskStatusSearchDisplay.TRIAGED: BugTaskStatus.TRIAGED,
             BugTaskStatusSearchDisplay.WONTFIX: BugTaskStatus.WONTFIX,
             }
-        observed = dict(
-            (status, normalize_bugtask_status(status))
-            for status in BugTaskStatusSearchDisplay.items)
+        observed = {
+            status: normalize_bugtask_status(status)
+            for status in BugTaskStatusSearchDisplay.items}
         self.assertEqual(expected, observed)
diff --git a/lib/lp/bugs/mail/bugnotificationbuilder.py b/lib/lp/bugs/mail/bugnotificationbuilder.py
index 9c95348..7b381a1 100644
--- a/lib/lp/bugs/mail/bugnotificationbuilder.py
+++ b/lib/lp/bugs/mail/bugnotificationbuilder.py
@@ -117,7 +117,7 @@ class BugNotificationBuilder:
         # Add the -Bug-Commenters header, a space-separated list of
         # distinct IDs of people who have commented on the bug. The
         # list is sorted to aid testing.
-        commenters = set(message.owner.name for message in bug.messages)
+        commenters = {message.owner.name for message in bug.messages}
         self.common_headers.append(
             ('X-Launchpad-Bug-Commenters', ' '.join(sorted(commenters))))
 
diff --git a/lib/lp/bugs/mail/handler.py b/lib/lp/bugs/mail/handler.py
index 7265336..fadb5bc 100644
--- a/lib/lp/bugs/mail/handler.py
+++ b/lib/lp/bugs/mail/handler.py
@@ -360,14 +360,14 @@ class MaloneHandler:
     # application/ms-tnef attachment are created by Outlook; they
     # seem to store no more than an RTF representation of an email.
 
-    irrelevant_content_types = set((
+    irrelevant_content_types = {
         'application/applefile',  # the resource fork of a MacOS file
         'application/pgp-signature',
         'application/pkcs7-signature',
         'application/x-pkcs7-signature',
         'text/x-vcard',
         'application/ms-tnef',
-        ))
+        }
 
     def processAttachments(self, bug, message, signed_mail):
         """Create Bugattachments for "reasonable" mail attachments.
diff --git a/lib/lp/bugs/model/bug.py b/lib/lp/bugs/model/bug.py
index 6088100..52c413a 100644
--- a/lib/lp/bugs/model/bug.py
+++ b/lib/lp/bugs/model/bug.py
@@ -287,7 +287,7 @@ def get_bug_tags_open_count(context_condition, user, tag_limit=0,
         )
     tags = {}
     if include_tags:
-        tags = dict((tag, 0) for tag in include_tags)
+        tags = {tag: 0 for tag in include_tags}
     where_conditions = [
         BugSummary.status.is_in(UNRESOLVED_BUGTASK_STATUSES),
         BugSummary.tag != None,
@@ -560,7 +560,7 @@ class Bug(SQLBase, InformationTypeMixin):
             # in storm with very large bugs by not joining and instead
             # querying a second time. If this starts to show high db
             # time, we can left outer join instead.
-            owner_ids = set(message.ownerID for message in messages)
+            owner_ids = {message.ownerID for message in messages}
             owner_ids.discard(None)
             if not owner_ids:
                 return
@@ -571,7 +571,7 @@ class Bug(SQLBase, InformationTypeMixin):
             # message, or joining in the database (though perhaps in
             # future we should do that), we do a single separate query
             # for the message content.
-            message_ids = set(message.id for message in messages)
+            message_ids = {message.id for message in messages}
             chunks = store.find(
                 MessageChunk, MessageChunk.messageID.is_in(message_ids))
             chunks.order_by(MessageChunk.id)
@@ -896,7 +896,7 @@ class Bug(SQLBase, InformationTypeMixin):
         clear_property_cache(self)
         # Ensure the unsubscriber is in the _known_viewer cache for the bug so
         # that the permissions are such that the operation can succeed.
-        get_property_cache(self)._known_viewers = set([unsubscribed_by.id])
+        get_property_cache(self)._known_viewers = {unsubscribed_by.id}
         if person is None:
             person = unsubscribed_by
 
@@ -1431,8 +1431,8 @@ class Bug(SQLBase, InformationTypeMixin):
 
     def getVisibleLinkedMergeProposals(self, user, eager_load=False):
         """See `IBug`."""
-        linked_merge_proposal_ids = set(
-            bmp.id for bmp in self.linked_merge_proposals)
+        linked_merge_proposal_ids = {
+            bmp.id for bmp in self.linked_merge_proposals}
         if not linked_merge_proposal_ids:
             return EmptyResultSet()
         else:
@@ -1863,7 +1863,7 @@ class Bug(SQLBase, InformationTypeMixin):
         """Set the tags from a list of strings."""
         # Sets provide an easy way to get the difference between the old and
         # new tags.
-        new_tags = set([tag.lower() for tag in tags])
+        new_tags = {tag.lower() for tag in tags}
         old_tags = set(self.tags)
         # The cache will be stale after we add/remove tags, clear it.
         del get_property_cache(self)._cached_tags
diff --git a/lib/lp/bugs/model/bugsubscriptionfilter.py b/lib/lp/bugs/model/bugsubscriptionfilter.py
index c3568d6..bf01a36 100644
--- a/lib/lp/bugs/model/bugsubscriptionfilter.py
+++ b/lib/lp/bugs/model/bugsubscriptionfilter.py
@@ -186,11 +186,11 @@ class BugSubscriptionFilter(StormBase):
         # Deal with other tags.
         tags = tags - wildcards
         store = IStore(BugSubscriptionFilterTag)
-        current_tag_filters = dict(
-            (tag_filter.qualified_tag, tag_filter)
+        current_tag_filters = {
+            tag_filter.qualified_tag: tag_filter
             for tag_filter in store.find(
                 BugSubscriptionFilterTag,
-                BugSubscriptionFilterTag.filter == self))
+                BugSubscriptionFilterTag.filter == self)}
         # Remove unused tags.
         for tag in set(current_tag_filters).difference(tags):
             tag_filter = current_tag_filters.pop(tag)
diff --git a/lib/lp/bugs/model/bugtarget.py b/lib/lp/bugs/model/bugtarget.py
index f7272d3..0f7f748 100644
--- a/lib/lp/bugs/model/bugtarget.py
+++ b/lib/lp/bugs/model/bugtarget.py
@@ -150,7 +150,7 @@ class OfficialBugTagTargetMixin:
 
     def _setOfficialTags(self, tags):
         """Set the official bug tags from a list of strings."""
-        new_tags = set([tag.lower() for tag in tags])
+        new_tags = {tag.lower() for tag in tags}
         old_tags = set(self.official_bug_tags)
         added_tags = new_tags.difference(old_tags)
         removed_tags = old_tags.difference(new_tags)
diff --git a/lib/lp/bugs/model/bugtask.py b/lib/lp/bugs/model/bugtask.py
index 14eeec1..dff8df5 100644
--- a/lib/lp/bugs/model/bugtask.py
+++ b/lib/lp/bugs/model/bugtask.py
@@ -1397,8 +1397,8 @@ class BugTaskSet:
             Bug,
             BugTag,
             )
-        bugtask_ids = set(bugtask.id for bugtask in bugtasks)
-        bug_ids = set(bugtask.bug_id for bugtask in bugtasks)
+        bugtask_ids = {bugtask.id for bugtask in bugtasks}
+        bug_ids = {bugtask.bug_id for bugtask in bugtasks}
         tags = IStore(BugTag).find(
             (BugTag.tag, BugTask.id),
             BugTask.bug == Bug.id,
@@ -1418,8 +1418,8 @@ class BugTaskSet:
             [bugtask.assignee_id for bugtask in bugtasks] +
             [bugtask.bug.ownerID for bugtask in bugtasks])
         people = getUtility(IPersonSet).getPrecachedPersonsFromIDs(people_ids)
-        return dict(
-            (person.id, person) for person in people)
+        return {
+            person.id: person for person in people}
 
     def getBugTaskBadgeProperties(self, bugtasks):
         """See `IBugTaskSet`."""
@@ -1427,11 +1427,11 @@ class BugTaskSet:
         from lp.bugs.model.bug import Bug
         from lp.bugs.model.bugbranch import BugBranch
 
-        bug_ids = set(bugtask.bug_id for bugtask in bugtasks)
-        bug_ids_with_specifications = set(
+        bug_ids = {bugtask.bug_id for bugtask in bugtasks}
+        bug_ids_with_specifications = {
             int(id) for _, id in getUtility(IXRefSet).findFromMany(
                 [(u'bug', six.text_type(bug_id)) for bug_id in bug_ids],
-                types=[u'specification']).keys())
+                types=[u'specification']).keys()}
         bug_ids_with_branches = set(IStore(BugBranch).find(
                 BugBranch.bug_id, BugBranch.bug_id.is_in(bug_ids)))
         # Badging looks up milestones too : eager load into the storm cache.
@@ -1445,9 +1445,9 @@ class BugTaskSet:
         # Check if the bugs are cached. If not, cache all uncached bugs
         # at once to avoid one query per bugtask. We could rely on the
         # Storm cache, but this is explicit.
-        bugs = dict(
-            (bug.id, bug)
-            for bug in IStore(Bug).find(Bug, Bug.id.is_in(bug_ids)).cached())
+        bugs = {
+            bug.id: bug
+            for bug in IStore(Bug).find(Bug, Bug.id.is_in(bug_ids)).cached()}
         uncached_ids = bug_ids.difference(bug_id for bug_id in bugs)
         if len(uncached_ids) > 0:
             bugs.update(dict(IStore(Bug).find((Bug.id, Bug),
@@ -1474,7 +1474,7 @@ class BugTaskSet:
         # Query the database, returning the results in a dictionary:
         if len(task_ids) > 0:
             tasks = IStore(BugTask).find(BugTask, BugTask.id.is_in(task_ids))
-            return dict([(task.id, task) for task in tasks])
+            return {task.id: task for task in tasks}
         else:
             return {}
 
@@ -1715,9 +1715,9 @@ class BugTaskSet:
             privacy=bug_privacy_filter)
         cur = cursor()
         cur.execute(query)
-        return dict(
-            (get_bugtask_status(status_id), count)
-            for (status_id, count) in cur.fetchall())
+        return {
+            get_bugtask_status(status_id): count
+            for (status_id, count) in cur.fetchall()}
 
     def findExpirableBugTasks(self, min_days_old, user,
                               bug=None, target=None, limit=None):
@@ -1894,7 +1894,7 @@ class BugTaskSet:
     def getBugCountsForPackages(self, user, packages):
         """See `IBugTaskSet`."""
         distributions = sorted(
-            set(package.distribution for package in packages),
+            {package.distribution for package in packages},
             key=attrgetter('name'))
         counts = []
         for distribution in distributions:
@@ -1955,9 +1955,9 @@ class BugTaskSet:
 
         # Only packages with open bugs were included in the query. Let's
         # add the rest of the packages as well.
-        all_packages = set(
+        all_packages = {
             (distro_package.distribution, distro_package.sourcepackagename)
-            for distro_package in packages)
+            for distro_package in packages}
         for distribution, sourcepackagename in all_packages.difference(
                 packages_with_bugs):
             package_counts = dict(
diff --git a/lib/lp/bugs/model/bugtasksearch.py b/lib/lp/bugs/model/bugtasksearch.py
index 4599d67..fd1ec25 100644
--- a/lib/lp/bugs/model/bugtasksearch.py
+++ b/lib/lp/bugs/model/bugtasksearch.py
@@ -558,9 +558,9 @@ def _build_query(params):
 
         # It's much faster to query for a single archive, so don't
         # include partner unless we have to.
-        archive_ids = set(
+        archive_ids = {
             distroseries.distribution.getArchiveByComponent(c.name).id
-            for c in components)
+            for c in components}
 
         extra_clauses.append(
             BugTaskFlat.sourcepackagename_id.is_in(
@@ -806,13 +806,13 @@ def _process_order_by(params):
     else:
         in_unique_context = False
 
-    unambiguous_cols = set([
+    unambiguous_cols = {
         BugTaskFlat.date_last_updated,
         BugTaskFlat.datecreated,
         BugTaskFlat.bugtask_id,
         Bug.datecreated,
         BugTask.date_assigned,
-        ])
+        }
     if in_unique_context:
         unambiguous_cols.add(BugTaskFlat.bug)
 
@@ -907,7 +907,7 @@ def _build_status_clause(col, status):
         values = list(status.query_values)
         # Since INCOMPLETE isn't stored as a single value any more, we need to
         # expand it before generating the SQL.
-        old = set([BugTaskStatus.INCOMPLETE, BugTaskStatusSearch.INCOMPLETE])
+        old = {BugTaskStatus.INCOMPLETE, BugTaskStatusSearch.INCOMPLETE}
         accepted_values = list(set(values) - old)
         if len(accepted_values) < len(values):
             accepted_values.extend(DB_INCOMPLETE_BUGTASK_STATUSES)
@@ -1345,7 +1345,7 @@ def _make_cache_user_can_view_bug(user):
     userid = user.id
 
     def cache_user_can_view_bug(bugtask):
-        get_property_cache(bugtask.bug)._known_viewers = set([userid])
+        get_property_cache(bugtask.bug)._known_viewers = {userid}
         return bugtask
     return cache_user_can_view_bug
 
diff --git a/lib/lp/bugs/model/bugtracker.py b/lib/lp/bugs/model/bugtracker.py
index d89145d..57edcb6 100644
--- a/lib/lp/bugs/model/bugtracker.py
+++ b/lib/lp/bugs/model/bugtracker.py
@@ -558,7 +558,7 @@ class BugTracker(SQLBase):
 
     def _get_aliases(self):
         """See `IBugTracker.aliases`."""
-        alias_urls = set(alias.base_url for alias in self._bugtracker_aliases)
+        alias_urls = {alias.base_url for alias in self._bugtracker_aliases}
         # Although it does no harm if the current baseurl is also an
         # alias, we hide it and all its permutations to avoid
         # confusion.
@@ -572,8 +572,8 @@ class BugTracker(SQLBase):
         else:
             alias_urls = set(alias_urls)
 
-        current_aliases_by_url = dict(
-            (alias.base_url, alias) for alias in self._bugtracker_aliases)
+        current_aliases_by_url = {
+            alias.base_url: alias for alias in self._bugtracker_aliases}
         # Make a set of the keys, i.e. a set of current URLs.
         current_alias_urls = set(current_aliases_by_url)
 
diff --git a/lib/lp/bugs/model/cve.py b/lib/lp/bugs/model/cve.py
index 7e37d78..07c26db 100644
--- a/lib/lp/bugs/model/cve.py
+++ b/lib/lp/bugs/model/cve.py
@@ -203,10 +203,10 @@ class CveSet:
             Cve, Cve.sequence.is_in([seq for _, seq in bugcve_ids]))
 
         if cve_mapper is None:
-            cvemap = dict((cve.sequence, cve) for cve in cves)
+            cvemap = {cve.sequence: cve for cve in cves}
         else:
-            cvemap = dict((cve.sequence, cve_mapper(cve)) for cve in cves)
-        bugmap = dict((bug.id, bug) for bug in bugs)
+            cvemap = {cve.sequence: cve_mapper(cve) for cve in cves}
+        bugmap = {bug.id: bug for bug in bugs}
         return [
             (bugmap[bug_id], cvemap[cve_sequence])
             for bug_id, cve_sequence in bugcve_ids
diff --git a/lib/lp/bugs/model/personsubscriptioninfo.py b/lib/lp/bugs/model/personsubscriptioninfo.py
index a5a6651..d0da76e 100644
--- a/lib/lp/bugs/model/personsubscriptioninfo.py
+++ b/lib/lp/bugs/model/personsubscriptioninfo.py
@@ -267,9 +267,9 @@ class PersonSubscriptions(object):
                 'subscription': get_id(info.subscription),
                 'principal_is_reporter': info.principal_is_reporter,
                 # We won't add bugtasks yet unless we need them.
-                'bug_supervisor_pillars': sorted(set(
+                'bug_supervisor_pillars': sorted({
                     get_id(d['pillar']) for d
-                    in info.bug_supervisor_tasks)),
+                    in info.bug_supervisor_tasks}),
                 }
         direct = {}
         from_duplicate = {}
diff --git a/lib/lp/bugs/model/structuralsubscription.py b/lib/lp/bugs/model/structuralsubscription.py
index 8f02d00..c964d95 100644
--- a/lib/lp/bugs/model/structuralsubscription.py
+++ b/lib/lp/bugs/model/structuralsubscription.py
@@ -563,7 +563,7 @@ def _get_structural_subscriptions(find, targets, *conditions):
                     get_structural_subscription_targets.
     :param conditions: additional conditions to filter the results.
     """
-    targets = set(target for bugtask, target in targets)
+    targets = {target for bugtask, target in targets}
     target_descriptions = [
         IStructuralSubscriptionTargetHelper(bugtarget).join
         for bugtarget in targets]
diff --git a/lib/lp/bugs/model/tests/test_bug.py b/lib/lp/bugs/model/tests/test_bug.py
index 3ce02e0..d5bda2a 100644
--- a/lib/lp/bugs/model/tests/test_bug.py
+++ b/lib/lp/bugs/model/tests/test_bug.py
@@ -133,7 +133,7 @@ class TestBug(TestCaseWithFactory):
             bug.subscribe(team2, person)
             bug.subscribe(person, person)
         self.assertEqual(
-            set([person, team1, team2]),
+            {person, team1, team2},
             set(bug.getSubscribersForPerson(person)))
 
     def test_get_subscribers_for_person_from_duplicates_too(self):
@@ -148,7 +148,7 @@ class TestBug(TestCaseWithFactory):
             bug.subscribe(person, person)
             bug.markAsDuplicate(real_bug)
         self.assertEqual(
-            set([person, team1, team2]),
+            {person, team1, team2},
             set(real_bug.getSubscribersForPerson(person)))
 
     def test_getSubscriptionsFromDuplicates(self):
@@ -704,9 +704,9 @@ class TestBugPrivateAndSecurityRelatedUpdatesProject(TestCaseWithFactory):
 
         (bug, bug_owner, bugtask_a, bugtask_b, default_bugtask) = (
             self.createBugTasksAndSubscribers())
-        initial_subscribers = set((
+        initial_subscribers = {
             self.factory.makePerson(name='subscriber'), bugtask_a.owner,
-            bug_owner))
+            bug_owner}
         initial_subscribers.update(bug.getDirectSubscribers())
 
         with person_logged_in(bug_owner):
@@ -726,8 +726,8 @@ class TestBugPrivateAndSecurityRelatedUpdatesProject(TestCaseWithFactory):
 
         (bug, bug_owner, bugtask_a, bugtask_b, default_bugtask) = (
                 self.createBugTasksAndSubscribers())
-        initial_subscribers = set((
-            self.factory.makePerson(name='subscriber'), bug_owner))
+        initial_subscribers = {
+            self.factory.makePerson(name='subscriber'), bug_owner}
 
         with person_logged_in(bug_owner):
             for subscriber in initial_subscribers:
@@ -745,9 +745,9 @@ class TestBugPrivateAndSecurityRelatedUpdatesProject(TestCaseWithFactory):
 
         (bug, bug_owner, bugtask_a, bugtask_b, default_bugtask) = (
             self.createBugTasksAndSubscribers(private_security_related=True))
-        initial_subscribers = set((
+        initial_subscribers = {
             self.factory.makePerson(), bug_owner, bugtask_a.pillar.driver,
-            bugtask_a.pillar.bug_supervisor))
+            bugtask_a.pillar.bug_supervisor}
 
         with person_logged_in(bug_owner):
             for subscriber in initial_subscribers:
@@ -756,7 +756,7 @@ class TestBugPrivateAndSecurityRelatedUpdatesProject(TestCaseWithFactory):
             bug.transitionToInformationType(
                 InformationType.PUBLICSECURITY, who)
             subscribers = bug.getDirectSubscribers()
-        expected_subscribers = set((default_bugtask.pillar.driver, bug_owner))
+        expected_subscribers = {default_bugtask.pillar.driver, bug_owner}
         expected_subscribers.update(initial_subscribers)
         self.assertContentEqual(expected_subscribers, subscribers)
 
@@ -766,9 +766,9 @@ class TestBugPrivateAndSecurityRelatedUpdatesProject(TestCaseWithFactory):
 
         (bug, bug_owner, bugtask_a, bugtask_b, default_bugtask) = (
             self.createBugTasksAndSubscribers(private_security_related=True))
-        initial_subscribers = set((
+        initial_subscribers = {
             self.factory.makePerson(name='subscriber'), bug_owner,
-            bugtask_a.pillar.driver))
+            bugtask_a.pillar.driver}
 
         with person_logged_in(bug_owner):
             for subscriber in initial_subscribers:
diff --git a/lib/lp/bugs/model/tests/test_bugsubscriptioninfo.py b/lib/lp/bugs/model/tests/test_bugsubscriptioninfo.py
index b3d6a24..9a1ad47 100644
--- a/lib/lp/bugs/model/tests/test_bugsubscriptioninfo.py
+++ b/lib/lp/bugs/model/tests/test_bugsubscriptioninfo.py
@@ -61,9 +61,9 @@ class TestSubscriptionRelatedSets(TestCaseWithFactory):
         super(TestSubscriptionRelatedSets, self).setUp()
         make_person = lambda displayname, name: (
             self.factory.makePerson(displayname=displayname, name=name))
-        subscribers = dict(
-            (name_pair, make_person(*name_pair))
-            for name_pair in self.name_pairs)
+        subscribers = {
+            name_pair: make_person(*name_pair)
+            for name_pair in self.name_pairs}
         self.subscribers_set = frozenset(six.itervalues(subscribers))
         self.subscribers_sorted = tuple(
             subscribers[name_pair] for name_pair in self.name_pairs_sorted)
diff --git a/lib/lp/bugs/model/tests/test_bugtask.py b/lib/lp/bugs/model/tests/test_bugtask.py
index e16ca9e..fdf666b 100644
--- a/lib/lp/bugs/model/tests/test_bugtask.py
+++ b/lib/lp/bugs/model/tests/test_bugtask.py
@@ -759,8 +759,8 @@ class TestBugTaskDelta(TestCaseWithFactory):
         # expected_delta is assumed to be None in the delta.
         delta = bug_task_after.getDelta(bug_task_before)
         expected_delta.setdefault('bugtask', bug_task_after)
-        names = set(
-            name for interface in providedBy(delta) for name in interface)
+        names = {
+            name for interface in providedBy(delta) for name in interface}
         for name in names:
             self.assertEqual(getattr(delta, name), expected_delta.get(name))
 
@@ -3282,8 +3282,8 @@ class TestTargetNameCache(TestCase):
             stderr=subprocess.PIPE, universal_newlines=True)
         (out, err) = process.communicate()
 
-        self.assertTrue(err.startswith(("INFO    Creating lockfile: "
-            "/var/lock/launchpad-launchpad-targetnamecacheupdater.lock")))
+        self.assertTrue(err.startswith("INFO    Creating lockfile: "
+            "/var/lock/launchpad-launchpad-targetnamecacheupdater.lock"))
         self.assertTrue('INFO    Updating targetname cache of bugtasks' in err)
         self.assertTrue('INFO    Calculating targets.' in err)
         self.assertTrue('INFO    Will check ' in err)
diff --git a/lib/lp/bugs/model/tests/test_bugtasksearch.py b/lib/lp/bugs/model/tests/test_bugtasksearch.py
index d4c909f..5357a66 100644
--- a/lib/lp/bugs/model/tests/test_bugtasksearch.py
+++ b/lib/lp/bugs/model/tests/test_bugtasksearch.py
@@ -1775,7 +1775,7 @@ class TestBugTaskSetStatusSearchClauses(TestCase):
         # in a "NOT".
         status = BugTaskStatus.INCOMPLETE
         base_query = self.searchClause(status)
-        expected_negative_query = 'NOT ({0})'.format(base_query)
+        expected_negative_query = 'NOT ({})'.format(base_query)
         self.assertEqual(
             expected_negative_query,
             self.searchClause(not_equals(status)))
diff --git a/lib/lp/bugs/scripts/bugsummaryrebuild.py b/lib/lp/bugs/scripts/bugsummaryrebuild.py
index ab72f5a..58daf6b 100644
--- a/lib/lp/bugs/scripts/bugsummaryrebuild.py
+++ b/lib/lp/bugs/scripts/bugsummaryrebuild.py
@@ -76,9 +76,9 @@ def get_bugtask_targets():
          )).config(distinct=True))
     # BugSummary counts package tasks in the packageless totals, so
     # ensure that there's also a packageless total for each distro(series).
-    new_targets.update(set(
+    new_targets.update({
         (p, ps, d, ds, None, None)
-        for (p, ps, d, ds, spn, ocip) in new_targets))
+        for (p, ps, d, ds, spn, ocip) in new_targets})
     return new_targets
 
 
@@ -111,8 +111,8 @@ def format_target(target):
 def _get_bugsummary_constraint_bits(target):
     raw_key = bug_target_to_key(target)
     # Map to ID columns to work around Storm bug #682989.
-    return dict(
-        ('%s_id' % k, v.id if v else None) for (k, v) in raw_key.items())
+    return {
+        '%s_id' % k: v.id if v else None for (k, v) in raw_key.items()}
 
 
 def get_bugsummary_constraint(target, cls=RawBugSummary):
@@ -233,10 +233,10 @@ def apply_bugsummary_changes(target, added, updated, removed):
 
 def rebuild_bugsummary_for_target(target, log):
     log.debug("Rebuilding %s" % format_target(target))
-    existing = dict(
-        (v[:-1], v[-1]) for v in get_bugsummary_rows(target))
-    expected = dict(
-        (v[:-1], v[-1]) for v in calculate_bugsummary_rows(target))
+    existing = {
+        v[:-1]: v[-1] for v in get_bugsummary_rows(target)}
+    expected = {
+        v[:-1]: v[-1] for v in calculate_bugsummary_rows(target)}
     added, updated, removed = calculate_bugsummary_changes(existing, expected)
     if added:
         log.debug('Added %r' % added)
diff --git a/lib/lp/bugs/scripts/checkwatches/core.py b/lib/lp/bugs/scripts/checkwatches/core.py
index c659a77..db59005 100644
--- a/lib/lp/bugs/scripts/checkwatches/core.py
+++ b/lib/lp/bugs/scripts/checkwatches/core.py
@@ -486,9 +486,9 @@ class CheckwatchesMaster(WorkingBase):
 
         with self.transaction:
             reload(bug_watches)
-            old_bug_watches = set(
+            old_bug_watches = {
                 bug_watch for bug_watch in bug_watches
-                if bug_watch.lastchecked is not None)
+                if bug_watch.lastchecked is not None}
             if len(old_bug_watches) == 0:
                 oldest_lastchecked = None
             else:
@@ -500,10 +500,10 @@ class CheckwatchesMaster(WorkingBase):
                     ACCEPTABLE_TIME_SKEW + timedelta(minutes=1))
             # Collate the remote IDs.
             remote_old_ids = sorted(
-                set(bug_watch.remotebug for bug_watch in old_bug_watches))
+                {bug_watch.remotebug for bug_watch in old_bug_watches})
             remote_new_ids = sorted(
-                set(bug_watch.remotebug for bug_watch in bug_watches
-                if bug_watch not in old_bug_watches))
+                {bug_watch.remotebug for bug_watch in bug_watches
+                if bug_watch not in old_bug_watches})
             # If the remote system is not configured to sync comments,
             # don't bother checking for any to push.
             if remotesystem.sync_comments:
diff --git a/lib/lp/bugs/scripts/tests/test_bugnotification.py b/lib/lp/bugs/scripts/tests/test_bugnotification.py
index d56ddf2..d5ec852 100644
--- a/lib/lp/bugs/scripts/tests/test_bugnotification.py
+++ b/lib/lp/bugs/scripts/tests/test_bugnotification.py
@@ -192,9 +192,9 @@ class FakeBugNotificationSetUtility:
 
     def getRecipientFilterData(self, bug, recipient_to_sources,
                                notifications):
-        return dict(
-            (recipient, {'sources': sources, 'filter descriptions': []})
-            for recipient, sources in recipient_to_sources.items())
+        return {
+            recipient: {'sources': sources, 'filter descriptions': []}
+            for recipient, sources in recipient_to_sources.items()}
 
 
 class MockBugActivity:
diff --git a/lib/lp/bugs/tests/externalbugtracker.py b/lib/lp/bugs/tests/externalbugtracker.py
index cdce45f..5caceae 100644
--- a/lib/lp/bugs/tests/externalbugtracker.py
+++ b/lib/lp/bugs/tests/externalbugtracker.py
@@ -115,8 +115,8 @@ def print_bugwatches(bug_watches, convert_remote_status=None):
     used to convert the watches' remote statuses to Launchpad
     BugTaskStatuses and these will be output instead.
     """
-    watches = dict((int(bug_watch.remotebug), bug_watch)
-        for bug_watch in bug_watches)
+    watches = {int(bug_watch.remotebug): bug_watch
+        for bug_watch in bug_watches}
 
     for remote_bug_id in sorted(watches.keys()):
         status = watches[remote_bug_id].remotestatus
@@ -542,7 +542,7 @@ class TestBugzillaXMLRPCTransport(RequestsTransport):
 
     @property
     def auth_cookie(self):
-        if len(set(cookie.domain for cookie in self.cookie_jar)) > 1:
+        if len({cookie.domain for cookie in self.cookie_jar}) > 1:
             raise AssertionError(
                 "There should only be cookies for one domain.")
 
@@ -719,9 +719,9 @@ class TestBugzillaXMLRPCTransport(RequestsTransport):
 
     def _copy_comment(self, comment, fields_to_return=None):
         # Copy wanted fields.
-        return dict(
-            (key, value) for (key, value) in six.iteritems(comment)
-            if fields_to_return is None or key in fields_to_return)
+        return {
+            key: value for (key, value) in six.iteritems(comment)
+            if fields_to_return is None or key in fields_to_return}
 
     def comments(self, arguments):
         """Return comments for a given set of bugs."""
@@ -1389,7 +1389,7 @@ class TestTracXMLRPCTransport(RequestsTransport):
         #     this method. See bugs 203564, 158703 and 158705.
 
         # We sort the list of bugs for the sake of testing.
-        bug_ids = sorted([bug_id for bug_id in self.remote_bugs.keys()])
+        bug_ids = sorted(bug_id for bug_id in self.remote_bugs.keys())
         bugs_to_return = []
         missing_bugs = []
 
@@ -1476,8 +1476,8 @@ class TestTracXMLRPCTransport(RequestsTransport):
 
         # For each of the missing ones, return a dict with a type of
         # 'missing'.
-        comment_ids_to_return = sorted([
-            comment['id'] for comment in comments_to_return])
+        comment_ids_to_return = sorted(
+            comment['id'] for comment in comments_to_return)
         missing_comments = [
             {'id': comment_id, 'type': 'missing'}
             for comment_id in comments
diff --git a/lib/lp/bugs/tests/test_bug_messages_webservice.py b/lib/lp/bugs/tests/test_bug_messages_webservice.py
index 44393d5..96c7f2e 100644
--- a/lib/lp/bugs/tests/test_bug_messages_webservice.py
+++ b/lib/lp/bugs/tests/test_bug_messages_webservice.py
@@ -91,16 +91,16 @@ class TestBugMessage(TestCaseWithFactory):
         # are the same set.
         with admin_logged_in():
             bug = self.factory.makeBug()
-            created_attachment_ids = set(
-                self.factory.makeBugAttachment(bug).id for i in range(3))
+            created_attachment_ids = {
+                self.factory.makeBugAttachment(bug).id for i in range(3)}
             bug_url = api_url(bug)
         self.assertThat(created_attachment_ids, HasLength(3))
 
         webservice = webservice_for_person(None)
         bug_attachments = webservice.get(
             bug_url + '/attachments').jsonBody()['entries']
-        bug_attachment_ids = set(
-            int(att['self_link'].rsplit('/', 1)[1]) for att in bug_attachments)
+        bug_attachment_ids = {
+            int(att['self_link'].rsplit('/', 1)[1]) for att in bug_attachments}
         self.assertContentEqual(created_attachment_ids, bug_attachment_ids)
 
         messages = webservice.get(bug_url + '/messages').jsonBody()['entries']
@@ -110,9 +110,9 @@ class TestBugMessage(TestCaseWithFactory):
             attachments = webservice.get(attachments_url).jsonBody()['entries']
             self.assertThat(attachments, HasLength(1))
             message_attachments.append(attachments[0])
-        message_attachment_ids = set(
+        message_attachment_ids = {
             int(att['self_link'].rsplit('/', 1)[1])
-            for att in message_attachments)
+            for att in message_attachments}
         self.assertContentEqual(bug_attachment_ids, message_attachment_ids)
 
 
diff --git a/lib/lp/bugs/tests/test_bugchanges.py b/lib/lp/bugs/tests/test_bugchanges.py
index 5786c0e..71daeab 100644
--- a/lib/lp/bugs/tests/test_bugchanges.py
+++ b/lib/lp/bugs/tests/test_bugchanges.py
@@ -83,9 +83,9 @@ class TestBugChanges(TestCaseWithFactory):
         if bug is None:
             bug = self.bug
         old_activities = set(bug.activity)
-        old_notification_ids = set(
+        old_notification_ids = {
             notification.id for notification in IStore(BugNotification).find(
-                BugNotification, bug=bug))
+                BugNotification, bug=bug)}
 
         if append:
             self.old_activities.update(old_activities)
@@ -173,23 +173,23 @@ class TestBugChanges(TestCaseWithFactory):
                         level=BugNotificationLevel.METADATA)
                 self.assertEqual(
                     set(expected_recipients),
-                    set(recipient.person
-                        for recipient in added_notification.recipients))
+                    {recipient.person
+                        for recipient in added_notification.recipients})
                 if expected_recipient_reasons:
                     self.assertEqual(
                         set(expected_recipient_reasons),
-                        set(recipient.reason_header
-                            for recipient in added_notification.recipients))
+                        {recipient.reason_header
+                            for recipient in added_notification.recipients})
 
     def assertRecipients(self, expected_recipients):
         notifications = self.getNewNotifications()
         notifications, omitted, messages = construct_email_notifications(
             notifications)
-        recipients = set(message['to'] for message in messages)
+        recipients = {message['to'] for message in messages}
 
         self.assertEqual(
-            set(recipient.preferredemail.email
-                for recipient in expected_recipients),
+            {recipient.preferredemail.email
+                for recipient in expected_recipients},
             recipients)
 
     def test_subscribe(self):
diff --git a/lib/lp/bugs/tests/test_bugnotification.py b/lib/lp/bugs/tests/test_bugnotification.py
index c1d673e..e58328d 100644
--- a/lib/lp/bugs/tests/test_bugnotification.py
+++ b/lib/lp/bugs/tests/test_bugnotification.py
@@ -373,9 +373,9 @@ class TestNotificationsForDuplicates(TestCaseWithFactory):
             self.dupe_bug.owner, subject='subject', content='content')
         latest_notification = IStore(BugNotification).find(
             BugNotification).order_by(BugNotification.id).last()
-        recipients = set(
+        recipients = {
             recipient.person
-            for recipient in latest_notification.recipients)
+            for recipient in latest_notification.recipients}
         self.assertEqual(self.dupe_subscribers, recipients)
 
     def test_duplicate_edit_notifications(self):
@@ -385,9 +385,9 @@ class TestNotificationsForDuplicates(TestCaseWithFactory):
             self.dupe_bug.description = 'A changed description'
         latest_notification = IStore(BugNotification).find(
             BugNotification).order_by(BugNotification.id).last()
-        recipients = set(
+        recipients = {
             recipient.person
-            for recipient in latest_notification.recipients)
+            for recipient in latest_notification.recipients}
         self.assertEqual(self.dupe_subscribers, recipients)
 
     def test_branch_linked_notification(self):
@@ -400,9 +400,9 @@ class TestNotificationsForDuplicates(TestCaseWithFactory):
         self.dupe_bug.linkBranch(branch, self.dupe_bug.owner)
         latest_notification = IStore(BugNotification).find(
             BugNotification).order_by(BugNotification.id).last()
-        recipients = set(
+        recipients = {
             recipient.person
-            for recipient in latest_notification.recipients)
+            for recipient in latest_notification.recipients}
         self.assertEqual(self.dupe_subscribers, recipients)
 
 
diff --git a/lib/lp/bugs/tests/test_bugwatch.py b/lib/lp/bugs/tests/test_bugwatch.py
index 7b1ac7c..6dca2df 100644
--- a/lib/lp/bugs/tests/test_bugwatch.py
+++ b/lib/lp/bugs/tests/test_bugwatch.py
@@ -584,7 +584,7 @@ class TestBugWatchSetBulkOperations(TestCaseWithFactory):
     def test_bulkAddActivity_with_iterator(self):
         # Any iterator can be passed in.
         getUtility(IBugWatchSet).bulkAddActivity(
-            (bug_watch for bug_watch in self.bug_watches))
+            bug_watch for bug_watch in self.bug_watches)
         self._checkActivityForBugWatches(
             BugWatchActivityStatus.SYNC_SUCCEEDED, None, None)
 
diff --git a/lib/lp/bugs/tests/test_structuralsubscription.py b/lib/lp/bugs/tests/test_structuralsubscription.py
index 334cfcf..d67bba2 100644
--- a/lib/lp/bugs/tests/test_structuralsubscription.py
+++ b/lib/lp/bugs/tests/test_structuralsubscription.py
@@ -491,8 +491,8 @@ class TestGetStructuralSubscriptionTargets(TestCaseWithFactory):
         bug = self.factory.makeBug(target=product, milestone=milestone)
         bugtask = bug.bugtasks[0]
         result = get_structural_subscription_targets(bug.bugtasks)
-        self.assertEqual(set(result), set(
-            ((bugtask, product), (bugtask, milestone))))
+        self.assertEqual(set(result), {
+            (bugtask, product), (bugtask, milestone)})
 
     def test_sourcepackage_target(self):
         actor = self.factory.makePerson()
@@ -506,9 +506,9 @@ class TestGetStructuralSubscriptionTargets(TestCaseWithFactory):
         product_bugtask = bug.bugtasks[0]
         sourcepackage_bugtask = bug.bugtasks[1]
         result = get_structural_subscription_targets(bug.bugtasks)
-        self.assertEqual(set(result), set(
-            ((product_bugtask, product),
-             (sourcepackage_bugtask, distroseries))))
+        self.assertEqual(set(result), {
+            (product_bugtask, product),
+             (sourcepackage_bugtask, distroseries)})
 
     def test_distribution_source_package_target(self):
         actor = self.factory.makePerson()
@@ -522,10 +522,10 @@ class TestGetStructuralSubscriptionTargets(TestCaseWithFactory):
         product_bugtask = bug.bugtasks[0]
         dist_sourcepackage_bugtask = bug.bugtasks[1]
         result = get_structural_subscription_targets(bug.bugtasks)
-        self.assertEqual(set(result), set(
-            ((product_bugtask, product),
+        self.assertEqual(set(result), {
+            (product_bugtask, product),
              (dist_sourcepackage_bugtask, dist_sourcepackage),
-             (dist_sourcepackage_bugtask, distribution))))
+             (dist_sourcepackage_bugtask, distribution)})
 
     def test_product_with_project_group(self):
         # get_structural_subscription_targets() will yield both a
@@ -541,7 +541,7 @@ class TestGetStructuralSubscriptionTargets(TestCaseWithFactory):
         bug = self.factory.makeBug(target=product)
         result = get_structural_subscription_targets(bug.bugtasks)
         self.assertEqual(
-            set([(bug.bugtasks[0], product), (bug.bugtasks[0], projectgroup)]),
+            {(bug.bugtasks[0], product), (bug.bugtasks[0], projectgroup)},
             set(result))
 
 
@@ -580,7 +580,7 @@ class TestGetStructuralSubscriptionsForBug(TestCaseWithFactory):
         sub2 = self.milestone.addBugSubscription(
             self.subscriber, self.subscriber)
         subscriptions = self.getSubscriptions(self.subscriber)
-        self.assertEqual(set([sub1, sub2]), set(subscriptions))
+        self.assertEqual({sub1, sub2}, set(subscriptions))
 
     def test_two_bugtasks_one_subscription(self):
         sub = self.product.addBugSubscription(
@@ -598,7 +598,7 @@ class TestGetStructuralSubscriptionsForBug(TestCaseWithFactory):
         sub2 = product2.addBugSubscription(
             self.subscriber, self.subscriber)
         subscriptions = self.getSubscriptions(self.subscriber)
-        self.assertEqual(set([sub1, sub2]), set(subscriptions))
+        self.assertEqual({sub1, sub2}, set(subscriptions))
 
     def test_ignore_other_subscriptions(self):
         sub1 = self.product.addBugSubscription(
@@ -626,7 +626,7 @@ class TestGetStructuralSubscriptionsForBug(TestCaseWithFactory):
             team_sub = self.product.addBugSubscription(
                 self.team, self.team.teamowner)
         subscriptions = self.getSubscriptions(self.subscriber)
-        self.assertEqual(set([self_sub, team_sub]), set(subscriptions))
+        self.assertEqual({self_sub, team_sub}, set(subscriptions))
 
     def test_subscriptions_from_parent(self):
         # get_structural_subscriptions_for_bug() will return any
@@ -642,7 +642,7 @@ class TestGetStructuralSubscriptionsForBug(TestCaseWithFactory):
         bug = self.factory.makeBug(target=product)
         subscriptions = get_structural_subscriptions_for_bug(
             bug, subscriber)
-        self.assertEqual(set([self_sub]), set(subscriptions))
+        self.assertEqual({self_sub}, set(subscriptions))
 
 
 class TestGetStructuralSubscriptions(TestCaseWithFactory):
@@ -783,7 +783,7 @@ class TestGetStructuralSubscribers(TestCaseWithFactory):
 
         subscribers = get_structural_subscribers(bug, None, None, None)
         self.assertIsInstance(subscribers, RESULT_SETS)
-        self.assertEqual(set([subscriber1, subscriber2]), set(subscribers))
+        self.assertEqual({subscriber1, subscriber2}, set(subscribers))
 
     def test_getStructuralSubscribers_recipients(self):
         # If provided, get_structural_subscribers() calls the appropriate
diff --git a/lib/lp/bugs/tests/test_structuralsubscriptiontarget.py b/lib/lp/bugs/tests/test_structuralsubscriptiontarget.py
index 9d75005..696d7c5 100644
--- a/lib/lp/bugs/tests/test_structuralsubscriptiontarget.py
+++ b/lib/lp/bugs/tests/test_structuralsubscriptiontarget.py
@@ -473,7 +473,7 @@ class TestGetAllStructuralSubscriptionsForTarget(TestCaseWithFactory):
             team_sub = self.product.addBugSubscription(
                 self.team, self.team.teamowner)
         subscriptions = self.getSubscriptions()
-        self.assertEqual(set([self_sub, team_sub]), set(subscriptions))
+        self.assertEqual({self_sub, team_sub}, set(subscriptions))
 
     def test_subscribed_to_project_group(self):
         # If a user is subscribed to a project group, calls to
@@ -486,7 +486,7 @@ class TestGetAllStructuralSubscriptionsForTarget(TestCaseWithFactory):
             self.subscriber, self.subscriber)
         subscriptions = get_structural_subscriptions_for_target(
             product, self.subscriber)
-        self.assertEqual(set([projectgroup_sub]), set(subscriptions))
+        self.assertEqual({projectgroup_sub}, set(subscriptions))
 
 
 def distributionSourcePackageSetUp(test):
diff --git a/lib/lp/bugs/vocabularies.py b/lib/lp/bugs/vocabularies.py
index 8801a71..b4e5f2d 100644
--- a/lib/lp/bugs/vocabularies.py
+++ b/lib/lp/bugs/vocabularies.py
@@ -352,8 +352,8 @@ class BugTaskMilestoneVocabulary:
         self.default_bugtask = default_bugtask
         self._milestones = None
         if milestones is not None:
-            self._milestones = dict(
-                (str(milestone.id), milestone) for milestone in milestones)
+            self._milestones = {
+                str(milestone.id): milestone for milestone in milestones}
 
     def _load_milestones(self, bugtask):
         # If the milestones have not already been cached, load them for the
@@ -362,8 +362,8 @@ class BugTaskMilestoneVocabulary:
             bugtask_set = getUtility(IBugTaskSet)
             milestones = list(
                 bugtask_set.getBugTaskTargetMilestones([bugtask]))
-            self._milestones = dict(
-                (str(milestone.id), milestone) for milestone in milestones)
+            self._milestones = {
+                str(milestone.id): milestone for milestone in milestones}
         return self._milestones
 
     @property
diff --git a/lib/lp/buildmaster/manager.py b/lib/lp/buildmaster/manager.py
index f893d85..9cec957 100644
--- a/lib/lp/buildmaster/manager.py
+++ b/lib/lp/buildmaster/manager.py
@@ -140,9 +140,9 @@ class PrefetchedBuildCandidates:
         # each builder group, and then re-sort the combined list in exactly
         # the same way.
         grouped_candidates = sorted(
-            [(builder_group_key, self.candidates[builder_group_key][0])
+            ((builder_group_key, self.candidates[builder_group_key][0])
              for builder_group_key in builder_group_keys
-             if self.candidates[builder_group_key]],
+             if self.candidates[builder_group_key]),
             key=lambda key_candidate: self.sort_keys[key_candidate[1]])
         if grouped_candidates:
             builder_group_key, candidate_id = grouped_candidates[0]
@@ -264,9 +264,9 @@ class PrefetchedBuilderFactory(BaseBuilderFactory):
             ).find((Builder, BuildQueue)))
         getUtility(IBuilderSet).preloadProcessors(
             [b for b, _ in builders_and_current_bqs])
-        self.vitals_map = dict(
-            (b.name, extract_vitals_from_db(b, bq))
-            for b, bq in builders_and_current_bqs)
+        self.vitals_map = {
+            b.name: extract_vitals_from_db(b, bq)
+            for b, bq in builders_and_current_bqs}
         self.candidates = PrefetchedBuildCandidates(
             list(self.vitals_map.values()))
         transaction.abort()
@@ -736,8 +736,8 @@ class BuilddManager(service.Service):
 
     def checkForNewBuilders(self):
         """Add and return any new builders."""
-        new_builders = set(
-            vitals.name for vitals in self.builder_factory.iterVitals())
+        new_builders = {
+            vitals.name for vitals in self.builder_factory.iterVitals()}
         old_builders = set(self.current_builders)
         extra_builders = new_builders.difference(old_builders)
         self.current_builders.extend(extra_builders)
diff --git a/lib/lp/buildmaster/model/buildqueue.py b/lib/lp/buildmaster/model/buildqueue.py
index ac1ece2..6556b64 100644
--- a/lib/lp/buildmaster/model/buildqueue.py
+++ b/lib/lp/buildmaster/model/buildqueue.py
@@ -141,7 +141,7 @@ class BuildQueue(StormBase):
         from lp.buildmaster.model.buildfarmjob import BuildFarmJob
         queues = [removeSecurityProxy(bq) for bq in queues]
         load_related(BuildFarmJob, queues, ['_build_farm_job_id'])
-        bfj_to_bq = dict((bq._build_farm_job, bq) for bq in queues)
+        bfj_to_bq = {bq._build_farm_job: bq for bq in queues}
         key = attrgetter('_build_farm_job.job_type')
         for job_type, group in groupby(sorted(queues, key=key), key=key):
             source = getUtility(ISpecificBuildFarmJobSource, job_type.name)
@@ -267,8 +267,8 @@ class BuildQueueSet(object):
     def preloadForBuilders(self, builders):
         # Populate builders' currentjob cachedproperty.
         queues = load_referencing(BuildQueue, builders, ['builder_id'])
-        queue_builders = dict(
-            (queue.builder_id, queue) for queue in queues)
+        queue_builders = {
+            queue.builder_id: queue for queue in queues}
         for builder in builders:
             cache = get_property_cache(builder)
             cache.currentjob = queue_builders.get(builder.id, None)
@@ -282,9 +282,9 @@ class BuildQueueSet(object):
             BuildQueue._build_farm_job_id.is_in(
                 [removeSecurityProxy(b).build_farm_job_id for b in builds])))
         load_related(Builder, bqs, ['builder_id'])
-        prefetched_data = dict(
-            (removeSecurityProxy(buildqueue)._build_farm_job_id, buildqueue)
-            for buildqueue in bqs)
+        prefetched_data = {
+            removeSecurityProxy(buildqueue)._build_farm_job_id: buildqueue
+            for buildqueue in bqs}
         for build in builds:
             bq = prefetched_data.get(
                 removeSecurityProxy(build).build_farm_job_id)
diff --git a/lib/lp/buildmaster/tests/test_manager.py b/lib/lp/buildmaster/tests/test_manager.py
index fd84f13..cd02bce 100644
--- a/lib/lp/buildmaster/tests/test_manager.py
+++ b/lib/lp/buildmaster/tests/test_manager.py
@@ -1214,10 +1214,10 @@ class TestBuilddManager(TestCase):
         self._stub_out_scheduleNextScanCycle()
 
         manager = BuilddManager()
-        builder_names = set(
-            builder.name for builder in getUtility(IBuilderSet))
+        builder_names = {
+            builder.name for builder in getUtility(IBuilderSet)}
         scanners = manager.addScanForBuilders(builder_names)
-        scanner_names = set(scanner.builder_name for scanner in scanners)
+        scanner_names = {scanner.builder_name for scanner in scanners}
         self.assertEqual(builder_names, scanner_names)
 
     def test_startService_adds_scanBuilders_loop(self):
diff --git a/lib/lp/buildmaster/tests/test_webservice.py b/lib/lp/buildmaster/tests/test_webservice.py
index 34aeb90..d39292d 100644
--- a/lib/lp/buildmaster/tests/test_webservice.py
+++ b/lib/lp/buildmaster/tests/test_webservice.py
@@ -66,8 +66,8 @@ class TestBuildersCollection(TestCaseWithFactory):
 
         builders = self.webservice.get(
             '/builders', api_version='devel').jsonBody()
-        current_builds = dict(
-            (b['name'], b['current_build_link']) for b in builders['entries'])
+        current_builds = {
+            b['name']: b['current_build_link'] for b in builders['entries']}
         self.assertEqual(
             'tag:launchpad.net:2008:redacted', current_builds['restricted'])
         self.assertEqual(
diff --git a/lib/lp/charms/model/charmrecipe.py b/lib/lp/charms/model/charmrecipe.py
index 7629c1b..2ee38d4 100644
--- a/lib/lp/charms/model/charmrecipe.py
+++ b/lib/lp/charms/model/charmrecipe.py
@@ -487,7 +487,7 @@ class CharmRecipe(StormBase, WebhookTargetMixin):
             for charm_base in store.find(
                 CharmBase,
                 CharmBase.distro_series_id.is_in(
-                    set(das.distroseriesID for das in all_buildable_dases)))}
+                    {das.distroseriesID for das in all_buildable_dases}))}
         return [
             das for das in all_buildable_dases
             if self._isBuildableArchitectureAllowed(
diff --git a/lib/lp/code/browser/branch.py b/lib/lp/code/browser/branch.py
index 87b43b2..f6e5d03 100644
--- a/lib/lp/code/browser/branch.py
+++ b/lib/lp/code/browser/branch.py
@@ -676,7 +676,7 @@ class BranchEditFormView(LaunchpadEditFormView):
         # If we're stacked on a private branch, only show that
         # information type.
         if self.context.stacked_on and self.context.stacked_on.private:
-            shown_types = set([self.context.stacked_on.information_type])
+            shown_types = {self.context.stacked_on.information_type}
         else:
             shown_types = (
                 InformationType.PUBLIC,
diff --git a/lib/lp/code/browser/branchlisting.py b/lib/lp/code/browser/branchlisting.py
index 64355b2..d3ecb66 100644
--- a/lib/lp/code/browser/branchlisting.py
+++ b/lib/lp/code/browser/branchlisting.py
@@ -354,7 +354,7 @@ class BranchListingItemsMixin:
         spec_branches = getUtility(
             ISpecificationBranchSet).getSpecificationBranchesForBranches(
             self.visible_branches_for_view, self.view_user)
-        return set(spec_branch.branch.id for spec_branch in spec_branches)
+        return {spec_branch.branch.id for spec_branch in spec_branches}
 
     @cachedproperty
     def branch_ids_with_merge_proposals(self):
@@ -366,7 +366,7 @@ class BranchListingItemsMixin:
         branches = self.visible_branches_for_view
         collection = self.getBranchCollection()
         proposals = collection.getMergeProposals(for_branches=branches)
-        return set(proposal.source_branch.id for proposal in proposals)
+        return {proposal.source_branch.id for proposal in proposals}
 
     @cachedproperty
     def tip_revisions(self):
@@ -378,8 +378,8 @@ class BranchListingItemsMixin:
             revisions = []
 
         # Key the revisions by revision id.
-        revision_map = dict(
-            (revision.revision_id, revision) for revision in revisions)
+        revision_map = {
+            revision.revision_id: revision for revision in revisions}
 
         # Cache display information for authors of branches' respective
         # last revisions.
@@ -388,9 +388,9 @@ class BranchListingItemsMixin:
             need_icon=True)
 
         # Return a dict keyed on branch id.
-        return dict(
-            (branch.id, revision_map.get(branch.last_scanned_id))
-            for branch in self.visible_branches_for_view)
+        return {
+            branch.id: revision_map.get(branch.last_scanned_id)
+            for branch in self.visible_branches_for_view}
 
     def _createItem(self, branch):
         last_commit = self.tip_revisions[branch.id]
@@ -1321,8 +1321,8 @@ class GroupedDistributionSourcePackageBranchesView(LaunchpadView,
         # Sort the branches by the last modified date, and ignore any that are
         # official.
         ordered_branches = sorted(
-            [branch for branch in branches
-             if branch not in official_branches],
+            (branch for branch in branches
+             if branch not in official_branches),
             key=attrgetter('date_last_modified'), reverse=True)
         num_branches = len(ordered_branches)
         num_official = len(official_branches)
diff --git a/lib/lp/code/browser/branchmergeproposal.py b/lib/lp/code/browser/branchmergeproposal.py
index 96b22d8..b7c157a 100644
--- a/lib/lp/code/browser/branchmergeproposal.py
+++ b/lib/lp/code/browser/branchmergeproposal.py
@@ -157,7 +157,7 @@ def latest_proposals_for_each_branch(proposals):
             targets[target] = (proposal, date_created)
 
     return sorted(
-        [proposal for proposal, date_created in six.itervalues(targets)],
+        (proposal for proposal, date_created in six.itervalues(targets)),
         key=operator.attrgetter('date_created'), reverse=True)
 
 
diff --git a/lib/lp/code/browser/tests/test_branchlisting.py b/lib/lp/code/browser/tests/test_branchlisting.py
index 1c4ad36..3f33640 100644
--- a/lib/lp/code/browser/tests/test_branchlisting.py
+++ b/lib/lp/code/browser/tests/test_branchlisting.py
@@ -129,7 +129,7 @@ class TestPersonOwnedBranchesView(TestCaseWithFactory,
     def test_branch_ids_with_bug_links(self):
         # _branches_for_current_batch should return a list of all branches in
         # the current batch.
-        branch_ids = set([self.branches[0].id])
+        branch_ids = {self.branches[0].id}
 
         view = create_initialized_view(
             self.barney, name="+branches", rootsite='code')
@@ -140,7 +140,7 @@ class TestPersonOwnedBranchesView(TestCaseWithFactory,
     def test_branch_ids_with_spec_links(self):
         # _branches_for_current_batch should return a list of all branches in
         # the current batch.
-        branch_ids = set([self.branches[1].id])
+        branch_ids = {self.branches[1].id}
 
         view = create_initialized_view(
             self.barney, name="+branches", rootsite='code')
@@ -151,7 +151,7 @@ class TestPersonOwnedBranchesView(TestCaseWithFactory,
     def test_branch_ids_with_merge_propoasls(self):
         # _branches_for_current_batch should return a list of all branches in
         # the current batch.
-        branch_ids = set([])
+        branch_ids = set()
         view = create_initialized_view(
             self.barney, name="+branches", rootsite='code')
         self.assertEqual(
@@ -680,8 +680,8 @@ class TestProjectGroupBranches(TestCaseWithFactory,
             self.projectgroup, name='+branches', rootsite='code')
         displayname = self.projectgroup.displayname
         expected_text = normalize_whitespace(
-            ("Launchpad does not know where any of %s's "
-             "projects host their code." % displayname))
+            "Launchpad does not know where any of %s's "
+             "projects host their code." % displayname)
         no_branch_div = find_tag_by_id(view(), "no-branchtable")
         text = normalize_whitespace(extract_text(no_branch_div))
         self.assertEqual(expected_text, text)
diff --git a/lib/lp/code/browser/tests/test_branchmergeproposal.py b/lib/lp/code/browser/tests/test_branchmergeproposal.py
index 18bd572..519ec9a 100644
--- a/lib/lp/code/browser/tests/test_branchmergeproposal.py
+++ b/lib/lp/code/browser/tests/test_branchmergeproposal.py
@@ -2044,16 +2044,16 @@ class TestBranchMergeProposalChangeStatusView(TestCaseWithFactory):
         # generated vocabulary.
         login_person(user)
         vocabulary = self._createView()._createStatusVocabulary()
-        vocab_tokens = sorted([term.token for term in vocabulary])
+        vocab_tokens = sorted(term.token for term in vocabulary)
         self.assertEqual(
             sorted(tokens), vocab_tokens)
 
     def assertAllStatusesAvailable(self, user, except_for=None):
         # All options should be available to the user, except for SUPERSEDED,
         # which is only provided through resubmit.
-        desired_statuses = set([
+        desired_statuses = {
             'WORK_IN_PROGRESS', 'NEEDS_REVIEW', 'MERGED', 'CODE_APPROVED',
-            'REJECTED'])
+            'REJECTED'}
         if except_for is not None:
             desired_statuses -= set(except_for)
         self.assertStatusVocabTokens(desired_statuses, user)
diff --git a/lib/lp/code/browser/tests/test_gitrepository.py b/lib/lp/code/browser/tests/test_gitrepository.py
index 367c2c0..faca389 100644
--- a/lib/lp/code/browser/tests/test_gitrepository.py
+++ b/lib/lp/code/browser/tests/test_gitrepository.py
@@ -1400,7 +1400,7 @@ class TestGitRepositoryPermissionsView(BrowserTestCase):
     def test__getRuleGrants(self):
         rule = self.factory.makeGitRule()
         grantees = sorted(
-            [self.factory.makePerson() for _ in range(3)],
+            (self.factory.makePerson() for _ in range(3)),
             key=attrgetter("name"))
         for grantee in (grantees[1], grantees[0], grantees[2]):
             self.factory.makeGitRuleGrant(rule=rule, grantee=grantee)
diff --git a/lib/lp/code/browser/tests/test_sourcepackagerecipe.py b/lib/lp/code/browser/tests/test_sourcepackagerecipe.py
index 3f12008..a54af33 100644
--- a/lib/lp/code/browser/tests/test_sourcepackagerecipe.py
+++ b/lib/lp/code/browser/tests/test_sourcepackagerecipe.py
@@ -308,10 +308,10 @@ class TestSourcePackageRecipeAddViewInitialValuesMixin:
         with person_logged_in(archive.owner):
             view = create_initialized_view(branch, '+new-recipe')
         series = set(view.initial_values['distroseries'])
-        initial_series = set([development, current])
+        initial_series = {development, current}
         self.assertEqual(initial_series, series.intersection(initial_series))
-        other_series = set(
-            [experimental, frozen, supported, obsolete, future])
+        other_series = {
+            experimental, frozen, supported, obsolete, future}
         self.assertEqual(set(), series.intersection(other_series))
 
 
@@ -440,7 +440,7 @@ class TestSourcePackageRecipeAddViewMixin:
         options = browser.getControl(name='field.owner.owner').displayOptions
         self.assertEqual(
             ['Good Chefs (good-chefs)', 'Master Chef (chef)'],
-            sorted([str(option) for option in options]))
+            sorted(str(option) for option in options))
 
     def test_create_new_recipe_team_owner(self):
         # New recipes can be owned by teams that the user is a member of.
@@ -1499,8 +1499,8 @@ class TestSourcePackageRecipeViewMixin:
         # Our recipe has a Warty distroseries
         self.assertEqual(['Warty'], build_distros)
         self.assertEqual(
-            set([2510]),
-            set(build.buildqueue_record.lastscore for build in builds))
+            {2510},
+            {build.buildqueue_record.lastscore for build in builds})
 
     def test_request_daily_builds_disabled_archive(self):
         # Requesting a daily build from a disabled archive is a user error.
diff --git a/lib/lp/code/browser/tests/test_tales.py b/lib/lp/code/browser/tests/test_tales.py
index 8452d35..1f928f7 100644
--- a/lib/lp/code/browser/tests/test_tales.py
+++ b/lib/lp/code/browser/tests/test_tales.py
@@ -165,8 +165,8 @@ class TestPreviewDiffFormatter(TestCaseWithFactory):
 
     def test_fmt_stale_non_empty_diff(self):
         # If there is no diff, there is no link.
-        diffstat = dict(
-            (self.factory.getUniqueString(), (2, 3)) for x in range(23))
+        diffstat = {
+            self.factory.getUniqueString(): (2, 3) for x in range(23)}
         preview = self._createStalePreviewDiff(
             500, 89, 340, diffstat=diffstat)
         expected_diffstat = '<br/>'.join(
@@ -183,8 +183,8 @@ class TestPreviewDiffFormatter(TestCaseWithFactory):
 
     def test_fmt_stale_non_empty_diff_with_conflicts(self):
         # If there is no diff, there is no link.
-        diffstat = dict(
-            (self.factory.getUniqueString(), (2, 3)) for x in range(23))
+        diffstat = {
+            self.factory.getUniqueString(): (2, 3) for x in range(23)}
         preview = self._createStalePreviewDiff(
             500, 89, 340, 'conflicts', diffstat=diffstat)
         expected_diffstat = '<br/>'.join(
diff --git a/lib/lp/code/interfaces/tests/test_branch.py b/lib/lp/code/interfaces/tests/test_branch.py
index b2c987a..a9bb02b 100644
--- a/lib/lp/code/interfaces/tests/test_branch.py
+++ b/lib/lp/code/interfaces/tests/test_branch.py
@@ -37,8 +37,8 @@ class TestFormatSupport(TestCase):
     def breezy_is_subset(self, breezy_formats, launchpad_enum):
         """Ensure the Breezy format marker list is a subset of Launchpad."""
         breezy_format_strings = set(breezy_formats)
-        launchpad_format_strings = set(
-            six.ensure_binary(format.title) for format in launchpad_enum.items)
+        launchpad_format_strings = {
+            six.ensure_binary(format.title) for format in launchpad_enum.items}
         self.assertEqual(
             set(), breezy_format_strings.difference(launchpad_format_strings))
 
diff --git a/lib/lp/code/mail/tests/test_branchmergeproposal.py b/lib/lp/code/mail/tests/test_branchmergeproposal.py
index 06bc638..537918f 100644
--- a/lib/lp/code/mail/tests/test_branchmergeproposal.py
+++ b/lib/lp/code/mail/tests/test_branchmergeproposal.py
@@ -147,7 +147,7 @@ class TestMergeProposalMailing(TestCaseWithFactory):
             'Baz Qux <mp+%d@%s>' % (bmp.id, config.launchpad.code_domain),
             ctrl.from_addr)
         reviewer_id = format_address_for_person(reviewer)
-        self.assertEqual(set([reviewer_id, bmp.address]), set(ctrl.to_addrs))
+        self.assertEqual({reviewer_id, bmp.address}, set(ctrl.to_addrs))
         mailer.sendAll()
 
     def test_forCreation_without_commit_message(self):
@@ -304,7 +304,7 @@ class TestMergeProposalMailing(TestCaseWithFactory):
                                     bmp.registrant)
         reviewer = request.recipient
         reviewer_id = format_address_for_person(reviewer)
-        self.assertEqual(set([reviewer_id, bmp.address]), set(ctrl.to_addrs))
+        self.assertEqual({reviewer_id, bmp.address}, set(ctrl.to_addrs))
 
     def test_to_addrs_excludes_team_reviewers(self):
         """Addresses for the to header exclude requested team reviewers."""
@@ -318,7 +318,7 @@ class TestMergeProposalMailing(TestCaseWithFactory):
                                     subscriber)
         reviewer = bmp.target_branch.owner
         reviewer_id = format_address_for_person(reviewer)
-        self.assertEqual(set([reviewer_id, bmp.address]), set(ctrl.to_addrs))
+        self.assertEqual({reviewer_id, bmp.address}, set(ctrl.to_addrs))
 
     def test_to_addrs_excludes_people_with_hidden_addresses(self):
         """The to header excludes those with hidden addresses."""
diff --git a/lib/lp/code/model/branch.py b/lib/lp/code/model/branch.py
index 12cfdf4..9f8011b 100644
--- a/lib/lp/code/model/branch.py
+++ b/lib/lp/code/model/branch.py
@@ -249,9 +249,9 @@ class Branch(SQLBase, WebhookTargetMixin, BzrIdentityMixin):
             self.information_type not in PUBLIC_INFORMATION_TYPES):
             aasource = getUtility(IAccessArtifactSource)
             [abstract_artifact] = aasource.ensure([self])
-            wanted_links = set(
+            wanted_links = {
                 (abstract_artifact, policy) for policy in
-                getUtility(IAccessPolicySource).findByTeam([self.owner]))
+                getUtility(IAccessPolicySource).findByTeam([self.owner])}
         else:
             # We haven't yet quite worked out how distribution privacy
             # works, so only work for products for now.
@@ -940,9 +940,9 @@ class Branch(SQLBase, WebhookTargetMixin, BzrIdentityMixin):
         """See `IBranch`."""
         alteration_operations, deletion_operations, = (
             self._deletionRequirements(eager_load=eager_load))
-        result = dict(
-            (operation.affected_object, ('alter', operation.rationale)) for
-            operation in alteration_operations)
+        result = {
+            operation.affected_object: ('alter', operation.rationale) for
+            operation in alteration_operations}
         # Deletion entries should overwrite alteration entries.
         result.update(
             (operation.affected_object, ('delete', operation.rationale)) for
diff --git a/lib/lp/code/model/branchcollection.py b/lib/lp/code/model/branchcollection.py
index 524fa69..6ba75ec 100644
--- a/lib/lp/code/model/branchcollection.py
+++ b/lib/lp/code/model/branchcollection.py
@@ -245,8 +245,8 @@ class GenericBranchCollection:
         load_related(SourcePackageName, branches, ['sourcepackagenameID'])
         load_related(DistroSeries, branches, ['distroseriesID'])
         load_related(Product, branches, ['productID'])
-        caches = dict((branch.id, get_property_cache(branch))
-            for branch in branches)
+        caches = {branch.id: get_property_cache(branch)
+            for branch in branches}
         branch_ids = caches.keys()
         for cache in caches.values():
             cache._associatedProductSeries = []
@@ -326,7 +326,7 @@ class GenericBranchCollection:
                 *self._convertListingSortToOrderBy(sort_by))
 
         def do_eager_load(rows):
-            branch_ids = set(branch.id for branch in rows)
+            branch_ids = {branch.id for branch in rows}
             if not branch_ids:
                 return
             GenericBranchCollection.preloadDataForBranches(rows)
@@ -338,8 +338,8 @@ class GenericBranchCollection:
 
         def cache_permission(branch):
             if self._user:
-                get_property_cache(branch)._known_viewers = set(
-                    [self._user.id])
+                get_property_cache(branch)._known_viewers = {
+                    self._user.id}
             return branch
 
         eager_load_hook = (
@@ -531,8 +531,8 @@ class GenericBranchCollection:
         merge_proposals = self.getMergeProposals(
                 target_branch=branch, merged_revnos=rev_nos,
                 statuses=[BranchMergeProposalStatus.MERGED])
-        merge_proposal_revs = dict(
-                [(mp.merged_revno, mp) for mp in merge_proposals])
+        merge_proposal_revs = {
+                mp.merged_revno: mp for mp in merge_proposals}
         source_branch_ids = [mp.source_branch.id for mp in merge_proposals]
         linked_bugtasks = defaultdict(list)
 
diff --git a/lib/lp/code/model/branchjob.py b/lib/lp/code/model/branchjob.py
index 172f83c..5d7c0d8 100644
--- a/lib/lp/code/model/branchjob.py
+++ b/lib/lp/code/model/branchjob.py
@@ -690,7 +690,7 @@ class RevisionsAddedJob(BranchJobDerived):
                 proposals[source_id] = (proposal, date_created)
 
         return sorted(
-            [proposal for proposal, date_created in six.itervalues(proposals)],
+            (proposal for proposal, date_created in six.itervalues(proposals)),
             key=operator.attrgetter('date_created'), reverse=True)
 
     def getRevisionMessage(self, revision_id, revno):
diff --git a/lib/lp/code/model/branchlookup.py b/lib/lp/code/model/branchlookup.py
index 9648e2a..80bda43 100644
--- a/lib/lp/code/model/branchlookup.py
+++ b/lib/lp/code/model/branchlookup.py
@@ -274,7 +274,7 @@ class BranchLookup:
 
     def getByUrls(self, urls):
         """See `IBranchLookup`."""
-        return dict((url, self.getByUrl(url)) for url in set(urls))
+        return {url: self.getByUrl(url) for url in set(urls)}
 
     def getByUniqueName(self, unique_name):
         """Find a branch by its unique name.
diff --git a/lib/lp/code/model/branchmergeproposal.py b/lib/lp/code/model/branchmergeproposal.py
index c3d0c4d..4a82f5d 100644
--- a/lib/lp/code/model/branchmergeproposal.py
+++ b/lib/lp/code/model/branchmergeproposal.py
@@ -510,9 +510,9 @@ class BranchMergeProposal(SQLBase, BugLinkTargetMixin):
         current_bug_ids = set(current_bug_ids_from_source)
         new_bug_ids = self._fetchRelatedBugIDsFromSource()
         # Only remove links marked as originating in the source branch.
-        remove_bugs = load(Bug, set(
+        remove_bugs = load(Bug, {
             bug_id for bug_id in current_bug_ids - new_bug_ids
-            if current_bug_ids_from_source[bug_id]))
+            if current_bug_ids_from_source[bug_id]})
         add_bugs = load(Bug, new_bug_ids - current_bug_ids)
         if remove_bugs or add_bugs:
             janitor = getUtility(ILaunchpadCelebrities).janitor
@@ -852,8 +852,8 @@ class BranchMergeProposal(SQLBase, BugLinkTargetMixin):
         # a database query to identify if there are any active proposals
         # with the same source and target branches.
         self.syncUpdate()
-        review_requests = list(set(
-            (vote.reviewer, vote.review_type) for vote in self.votes))
+        review_requests = list({
+            (vote.reviewer, vote.review_type) for vote in self.votes})
         proposal = merge_source.addLandingTarget(
             registrant=registrant,
             merge_target=merge_target,
@@ -1215,9 +1215,9 @@ class BranchMergeProposal(SQLBase, BugLinkTargetMixin):
         """See `IBranchMergeProposal`."""
         diffs = Store.of(self).find(IncrementalDiff,
             IncrementalDiff.branch_merge_proposal_id == self.id)
-        diff_dict = dict(
-            ((diff.old_revision, diff.new_revision), diff)
-            for diff in diffs)
+        diff_dict = {
+            (diff.old_revision, diff.new_revision): diff
+            for diff in diffs}
         return [diff_dict.get(revisions) for revisions in revision_list]
 
     def scheduleDiffUpdates(self, return_jobs=True):
@@ -1344,8 +1344,8 @@ class BranchMergeProposal(SQLBase, BugLinkTargetMixin):
                          mp.prerequisite_git_path))
             person_ids.add(mp.registrantID)
             person_ids.add(mp.merge_reporterID)
-        git_repository_ids = set(
-            repository_id for repository_id, _ in git_ref_keys)
+        git_repository_ids = {
+            repository_id for repository_id, _ in git_ref_keys}
 
         branches = load_related(
             Branch, branch_merge_proposals, (
@@ -1476,7 +1476,7 @@ class BranchMergeProposalGetter:
             return {}
         ids = [proposal.id for proposal in proposals]
         store = Store.of(proposals[0])
-        result = dict([(proposal, []) for proposal in proposals])
+        result = {proposal: [] for proposal in proposals}
         # Make sure that the Person and the review comment are loaded in the
         # storm cache as the reviewer is displayed in a title attribute on the
         # merge proposal listings page, and the message is needed to get to
diff --git a/lib/lp/code/model/codereviewcomment.py b/lib/lp/code/model/codereviewcomment.py
index be85747..4b18adc 100644
--- a/lib/lp/code/model/codereviewcomment.py
+++ b/lib/lp/code/model/codereviewcomment.py
@@ -122,7 +122,7 @@ class CodeReviewComment(StormBase):
         attachments = [chunk.blob for chunk in self.message.chunks
                        if chunk.blob is not None]
         # Attachments to show.
-        good_mimetypes = set(['text/plain', 'text/x-diff', 'text/x-patch'])
+        good_mimetypes = {'text/plain', 'text/x-diff', 'text/x-patch'}
         display_attachments = [
             attachment for attachment in attachments
             if ((attachment.mimetype in good_mimetypes) or
diff --git a/lib/lp/code/model/diff.py b/lib/lp/code/model/diff.py
index abcb25c..13f633c 100644
--- a/lib/lp/code/model/diff.py
+++ b/lib/lp/code/model/diff.py
@@ -77,9 +77,9 @@ class Diff(SQLBase):
     def _get_diffstat(self):
         if self._diffstat is None:
             return None
-        return dict((key, tuple(value))
+        return {key: tuple(value)
                     for key, value
-                    in simplejson.loads(self._diffstat).items())
+                    in simplejson.loads(self._diffstat).items()}
 
     def _set_diffstat(self, diffstat):
         if diffstat is None:
@@ -385,13 +385,13 @@ class PreviewDiff(Storm):
             source_revision = bmp.source_branch.getBranchRevision(
                 revision_id=self.source_revision_id)
             if source_revision and source_revision.sequence:
-                source_rev = u'r{0}'.format(source_revision.sequence)
+                source_rev = u'r{}'.format(source_revision.sequence)
             else:
                 source_rev = self.source_revision_id
             target_revision = bmp.target_branch.getBranchRevision(
                 revision_id=self.target_revision_id)
             if target_revision and target_revision.sequence:
-                target_rev = u'r{0}'.format(target_revision.sequence)
+                target_rev = u'r{}'.format(target_revision.sequence)
             else:
                 target_rev = self.target_revision_id
         else:
@@ -402,7 +402,7 @@ class PreviewDiff(Storm):
             source_rev = self.source_revision_id[:7]
             target_rev = self.target_revision_id[:7]
 
-        return u'{0} into {1}'.format(source_rev, target_rev)
+        return u'{} into {}'.format(source_rev, target_rev)
 
     @property
     def has_conflicts(self):
diff --git a/lib/lp/code/model/gitcollection.py b/lib/lp/code/model/gitcollection.py
index 444a8eb..966ea02 100644
--- a/lib/lp/code/model/gitcollection.py
+++ b/lib/lp/code/model/gitcollection.py
@@ -252,7 +252,7 @@ class GenericGitCollection:
                 *self._convertListingSortToOrderBy(sort_by)))
 
         def do_eager_load(rows):
-            repository_ids = set(repository.id for repository in rows)
+            repository_ids = {repository.id for repository in rows}
             if not repository_ids:
                 return
             GenericGitCollection.preloadDataForRepositories(rows)
@@ -262,8 +262,8 @@ class GenericGitCollection:
 
         def cache_permission(repository):
             if self._user:
-                get_property_cache(repository)._known_viewers = set(
-                    [self._user.id])
+                get_property_cache(repository)._known_viewers = {
+                    self._user.id}
             return repository
 
         eager_load_hook = (
diff --git a/lib/lp/code/model/gitref.py b/lib/lp/code/model/gitref.py
index 8571c4a..4c79c28 100644
--- a/lib/lp/code/model/gitref.py
+++ b/lib/lp/code/model/gitref.py
@@ -456,7 +456,7 @@ class GitRefMixin:
         from lp.code.model.sourcepackagerecipedata import (
             SourcePackageRecipeData,
             )
-        revspecs = set([self.path, self.name])
+        revspecs = {self.path, self.name}
         if self.path == self.repository.default_branch:
             revspecs.add(None)
         recipes = SourcePackageRecipeData.findRecipes(
diff --git a/lib/lp/code/model/gitrepository.py b/lib/lp/code/model/gitrepository.py
index 796ab80..7a3a9fe 100644
--- a/lib/lp/code/model/gitrepository.py
+++ b/lib/lp/code/model/gitrepository.py
@@ -618,9 +618,9 @@ class GitRepository(StormBase, WebhookTargetMixin, AccessTokenTargetMixin,
             self.information_type not in PUBLIC_INFORMATION_TYPES):
             aasource = getUtility(IAccessArtifactSource)
             [abstract_artifact] = aasource.ensure([self])
-            wanted_links = set(
+            wanted_links = {
                 (abstract_artifact, policy) for policy in
-                getUtility(IAccessPolicySource).findByTeam([self.owner]))
+                getUtility(IAccessPolicySource).findByTeam([self.owner])}
         else:
             # We haven't yet quite worked out how distribution privacy
             # works, so only work for projects for now.
@@ -847,7 +847,7 @@ class GitRepository(StormBase, WebhookTargetMixin, AccessTokenTargetMixin,
     @staticmethod
     def fetchRefCommits(hosting_path, refs, logger=None):
         """See `IGitRepository`."""
-        oids = sorted(set(info["sha1"] for info in refs.values()))
+        oids = sorted({info["sha1"] for info in refs.values()})
         if not oids:
             return
         commits = parse_git_commits(
@@ -1318,7 +1318,7 @@ class GitRepository(StormBase, WebhookTargetMixin, AccessTokenTargetMixin,
             proposals = list(group)
             merges = hosting_client.detectMerges(
                 self.getInternalPath(), proposals[0].target_git_commit_sha1,
-                set(proposal.source_git_commit_sha1 for proposal in proposals))
+                {proposal.source_git_commit_sha1 for proposal in proposals})
             for proposal in proposals:
                 merged_revision_id = merges.get(
                     proposal.source_git_commit_sha1)
diff --git a/lib/lp/code/model/revision.py b/lib/lp/code/model/revision.py
index 4958e32..680f3a2 100644
--- a/lib/lp/code/model/revision.py
+++ b/lib/lp/code/model/revision.py
@@ -120,7 +120,7 @@ class Revision(SQLBase):
 
     def getProperties(self):
         """See `IRevision`."""
-        return dict((prop.name, prop.value) for prop in self.properties)
+        return {prop.name: prop.value for prop in self.properties}
 
     def allocateKarma(self, branch):
         """See `IRevision`."""
@@ -347,9 +347,9 @@ class RevisionSet:
                 author = None
             author_names.append(author)
         # Get or make every RevisionAuthor for these revisions.
-        revision_authors = dict(
-            (name, author.id) for name, author in
-            self.acquireRevisionAuthors(author_names).items())
+        revision_authors = {
+            name: author.id for name, author in
+            self.acquireRevisionAuthors(author_names).items()}
 
         # Collect all data for making Revision objects.
         data = []
@@ -367,8 +367,8 @@ class RevisionSet:
             Revision.revision_author_id), data, get_objects=True)
 
         # Map revision_id to Revision database ID.
-        revision_db_id = dict(
-            (rev.revision_id, rev.id) for rev in db_revisions)
+        revision_db_id = {
+            rev.revision_id: rev.id for rev in db_revisions}
 
         # Collect all data for making RevisionParent and RevisionProperty
         # objects.
diff --git a/lib/lp/code/model/seriessourcepackagebranch.py b/lib/lp/code/model/seriessourcepackagebranch.py
index 5aa7d7d..051d86e 100644
--- a/lib/lp/code/model/seriessourcepackagebranch.py
+++ b/lib/lp/code/model/seriessourcepackagebranch.py
@@ -103,7 +103,7 @@ class SeriesSourcePackageBranchSet:
 
     def findForBranches(self, branches):
         """See `IFindOfficialBranchLinks`."""
-        branch_ids = set(branch.id for branch in branches)
+        branch_ids = {branch.id for branch in branches}
         return IStore(SeriesSourcePackageBranch).find(
             SeriesSourcePackageBranch,
             SeriesSourcePackageBranch.branchID.is_in(branch_ids))
diff --git a/lib/lp/code/model/sourcepackagerecipebuild.py b/lib/lp/code/model/sourcepackagerecipebuild.py
index 3a4f0ba..f10ed3c 100644
--- a/lib/lp/code/model/sourcepackagerecipebuild.py
+++ b/lib/lp/code/model/sourcepackagerecipebuild.py
@@ -390,9 +390,9 @@ class SourcePackageRecipeBuild(SpecificBuildFarmJobSourceMixin,
 
     def getFileByName(self, filename):
         """See `ISourcePackageRecipeBuild`."""
-        files = dict((lfa.filename, lfa)
+        files = {lfa.filename: lfa
                      for lfa in [self.log, self.upload_log]
-                     if lfa is not None)
+                     if lfa is not None}
         try:
             return files[filename]
         except KeyError:
diff --git a/lib/lp/code/model/tests/test_branch.py b/lib/lp/code/model/tests/test_branch.py
index 9379266..16858d2 100644
--- a/lib/lp/code/model/tests/test_branch.py
+++ b/lib/lp/code/model/tests/test_branch.py
@@ -1783,7 +1783,7 @@ class StackedBranches(TestCaseWithFactory):
         branch = self.factory.makeAnyBranch()
         stacked_branch = self.factory.makeAnyBranch(stacked_on=branch)
         self.assertEqual(
-            set([stacked_branch]), set(branch.getStackedBranches()))
+            {stacked_branch}, set(branch.getStackedBranches()))
 
     def testMultipleBranchesStacked(self):
         # some_branch.getStackedBranches returns a collection of branches
@@ -1792,7 +1792,7 @@ class StackedBranches(TestCaseWithFactory):
         stacked_a = self.factory.makeAnyBranch(stacked_on=branch)
         stacked_b = self.factory.makeAnyBranch(stacked_on=branch)
         self.assertEqual(
-            set([stacked_a, stacked_b]), set(branch.getStackedBranches()))
+            {stacked_a, stacked_b}, set(branch.getStackedBranches()))
 
     def testNoBranchesStackedOn(self):
         # getStackedBranches returns an empty collection if there are no
@@ -1806,7 +1806,7 @@ class StackedBranches(TestCaseWithFactory):
         branch = self.factory.makeAnyBranch()
         stacked_branch = self.factory.makeAnyBranch(stacked_on=branch)
         self.assertEqual(
-            set([branch]), set(stacked_branch.getStackedOnBranches()))
+            {branch}, set(stacked_branch.getStackedOnBranches()))
 
     def testMultipleBranchesStackedOn(self):
         # some_branch.getStackedOnBranches returns a collection of branches
@@ -1815,7 +1815,7 @@ class StackedBranches(TestCaseWithFactory):
         stacked_b = self.factory.makeAnyBranch(stacked_on=stacked_a)
         branch = self.factory.makeAnyBranch(stacked_on=stacked_b)
         self.assertEqual(
-            set([stacked_a, stacked_b]), set(branch.getStackedOnBranches()))
+            {stacked_a, stacked_b}, set(branch.getStackedOnBranches()))
 
 
 class BranchAddLandingTarget(TestCaseWithFactory):
@@ -1976,9 +1976,9 @@ class BranchAddLandingTarget(TestCaseWithFactory):
         bmp = self.source._createMergeProposal(
             self.user, self.target, reviewers=[person1, person2],
             review_types=['review1', 'review2'])
-        votes = set((vote.reviewer, vote.review_type) for vote in bmp.votes)
+        votes = {(vote.reviewer, vote.review_type) for vote in bmp.votes}
         self.assertEqual(
-            set([(person1, 'review1'), (person2, 'review2')]), votes)
+            {(person1, 'review1'), (person2, 'review2')}, votes)
 
 
 class TestLandingCandidates(TestCaseWithFactory):
@@ -3161,9 +3161,9 @@ class TestScheduleDiffUpdates(TestCaseWithFactory):
         removeSecurityProxy(bmp2).target_branch.last_scanned_id = 'rev2'
         jobs = bmp1.source_branch.scheduleDiffUpdates()
         self.assertEqual(2, len(jobs))
-        bmps_to_update = set(
-            removeSecurityProxy(job).branch_merge_proposal for job in jobs)
-        self.assertEqual(set([bmp1, bmp2]), bmps_to_update)
+        bmps_to_update = {
+            removeSecurityProxy(job).branch_merge_proposal for job in jobs}
+        self.assertEqual({bmp1, bmp2}, bmps_to_update)
 
     def test_scheduleDiffUpdates_ignores_final(self):
         """Diffs for proposals in final states aren't updated."""
diff --git a/lib/lp/code/model/tests/test_branchjob.py b/lib/lp/code/model/tests/test_branchjob.py
index ad2dd1b..d3b7592 100644
--- a/lib/lp/code/model/tests/test_branchjob.py
+++ b/lib/lp/code/model/tests/test_branchjob.py
@@ -576,7 +576,7 @@ class TestRevisionsAddedJob(TestCaseWithFactory):
         graph = job.bzr_branch.repository.get_graph()
         self.addCleanup(job.bzr_branch.unlock)
         self.assertEqual(
-            set([b'rev2a-id', b'rev3-id', b'rev2b-id', b'rev2c-id']),
+            {b'rev2a-id', b'rev3-id', b'rev2b-id', b'rev2c-id'},
             job.getMergedRevisionIDs(b'rev2d-id', graph))
 
     def test_findRelatedBMP(self):
@@ -622,7 +622,7 @@ class TestRevisionsAddedJob(TestCaseWithFactory):
         self.addCleanup(job.bzr_branch.unlock)
         graph = job.bzr_branch.repository.get_graph()
         revision_ids = [b'rev2a-id', b'rev3-id', b'rev2b-id']
-        self.assertEqual(set(['foo@', 'bar@', 'baz@xxxxxxxxxx', 'qux@']),
+        self.assertEqual({'foo@', 'bar@', 'baz@xxxxxxxxxx', 'qux@'},
                          job.getAuthors(revision_ids, graph))
 
     def test_getAuthors_with_ghost(self):
@@ -632,7 +632,7 @@ class TestRevisionsAddedJob(TestCaseWithFactory):
         graph = job.bzr_branch.repository.get_graph()
         self.addCleanup(job.bzr_branch.unlock)
         revision_ids = [b'rev2a-id', b'rev3-id', b'rev2b-id', b'rev2c-id']
-        self.assertEqual(set(['foo@', 'bar@', 'baz@xxxxxxxxxx', 'qux@']),
+        self.assertEqual({'foo@', 'bar@', 'baz@xxxxxxxxxx', 'qux@'},
                          job.getAuthors(revision_ids, graph))
 
     def test_getRevisionMessage(self):
diff --git a/lib/lp/code/model/tests/test_branchmergeproposal.py b/lib/lp/code/model/tests/test_branchmergeproposal.py
index 3e58e46..ed4fdd4 100644
--- a/lib/lp/code/model/tests/test_branchmergeproposal.py
+++ b/lib/lp/code/model/tests/test_branchmergeproposal.py
@@ -399,7 +399,7 @@ class TestBranchMergeProposalTransitions(TestCaseWithFactory):
         proposal = self.factory.makeBranchMergeProposal()
         # It is always valid to go to the same state.
         self.assertValidTransitions(
-            set([BranchMergeProposalStatus.REJECTED]),
+            {BranchMergeProposalStatus.REJECTED},
             proposal, BranchMergeProposalStatus.REJECTED,
             proposal.source_branch.owner)
 
@@ -610,7 +610,7 @@ class TestMergeProposalAllComments(TestCase):
         comment3 = self.merge_proposal.createComment(
             self.merge_proposal.registrant, "Subject")
         self.assertEqual(
-            set([comment1, comment2, comment3]),
+            {comment1, comment2, comment3},
             set(self.merge_proposal.all_comments))
 
 
@@ -816,7 +816,7 @@ class TestMergeProposalNotification(WithVCSScenarios, TestCaseWithFactory):
         target_owner = bmp.merge_target.owner
         recipients = bmp.getNotificationRecipients(
             CodeReviewNotificationLevel.STATUS)
-        subscriber_set = set([source_owner, target_owner])
+        subscriber_set = {source_owner, target_owner}
         self.assertEqual(subscriber_set, set(recipients.keys()))
         source_subscriber = self.factory.makePerson()
         bmp.merge_source.subscribe(
@@ -856,12 +856,12 @@ class TestMergeProposalNotification(WithVCSScenarios, TestCaseWithFactory):
         # branches with full code review notification level set.
         source_owner = bmp.merge_source.owner
         target_owner = bmp.merge_target.owner
-        self.assertEqual(set([full_subscriber, status_subscriber,
-                              source_owner, target_owner]),
+        self.assertEqual({full_subscriber, status_subscriber,
+                              source_owner, target_owner},
                          set(recipients.keys()))
         recipients = bmp.getNotificationRecipients(
             CodeReviewNotificationLevel.FULL)
-        self.assertEqual(set([full_subscriber, source_owner, target_owner]),
+        self.assertEqual({full_subscriber, source_owner, target_owner},
                          set(recipients.keys()))
 
     def test_getNotificationRecipientsAnyBranch(self):
@@ -873,7 +873,7 @@ class TestMergeProposalNotification(WithVCSScenarios, TestCaseWithFactory):
         target_owner = bmp.merge_target.owner
         prerequisite_owner = bmp.merge_prerequisite.owner
         self.assertEqual(
-            set([source_owner, target_owner, prerequisite_owner]),
+            {source_owner, target_owner, prerequisite_owner},
             set(recipients.keys()))
         source_subscriber = self.factory.makePerson()
         bmp.merge_source.subscribe(source_subscriber,
@@ -890,9 +890,9 @@ class TestMergeProposalNotification(WithVCSScenarios, TestCaseWithFactory):
         recipients = bmp.getNotificationRecipients(
             CodeReviewNotificationLevel.FULL)
         self.assertEqual(
-            set([source_subscriber, target_subscriber,
+            {source_subscriber, target_subscriber,
                  prerequisite_subscriber, source_owner, target_owner,
-                 prerequisite_owner]),
+                 prerequisite_owner},
             set(recipients.keys()))
 
     def test_getNotificationRecipientsIncludesReviewers(self):
@@ -906,7 +906,7 @@ class TestMergeProposalNotification(WithVCSScenarios, TestCaseWithFactory):
         bmp.nominateReviewer(reviewer, registrant=source_owner)
         recipients = bmp.getNotificationRecipients(
             CodeReviewNotificationLevel.STATUS)
-        subscriber_set = set([source_owner, target_owner, reviewer])
+        subscriber_set = {source_owner, target_owner, reviewer}
         self.assertEqual(subscriber_set, set(recipients.keys()))
 
     def test_getNotificationRecipientsIncludesTeamReviewers(self):
@@ -921,7 +921,7 @@ class TestMergeProposalNotification(WithVCSScenarios, TestCaseWithFactory):
         bmp.nominateReviewer(reviewer, registrant=source_owner)
         recipients = bmp.getNotificationRecipients(
             CodeReviewNotificationLevel.STATUS)
-        subscriber_set = set([source_owner, target_owner, reviewer])
+        subscriber_set = {source_owner, target_owner, reviewer}
         self.assertEqual(subscriber_set, set(recipients.keys()))
 
     def test_getNotificationRecipients_Registrant(self):
@@ -971,7 +971,7 @@ class TestMergeProposalNotification(WithVCSScenarios, TestCaseWithFactory):
         bmp = self.makeBranchMergeProposal(source=branch)
         recipients = bmp.getNotificationRecipients(
             CodeReviewNotificationLevel.STATUS)
-        headers = set([reason.mail_header for reason in recipients.values()])
+        headers = {reason.mail_header for reason in recipients.values()}
         self.assertFalse("Owner" in headers)
 
     def test_getNotificationRecipients_Owner_not_subscribed(self):
@@ -1325,7 +1325,7 @@ class TestBranchMergeProposalGetterGetProposals(TestCaseWithFactory):
         # Helper method to return tuples of source branch details.
         results = BranchMergeProposalGetter.getProposalsForContext(
             context, status, visible_by_user)
-        return sorted([bmp.source_branch.unique_name for bmp in results])
+        return sorted(bmp.source_branch.unique_name for bmp in results)
 
     def test_getProposalsForParticipant(self):
         # It's possible to get all the merge proposals for a single
@@ -1848,7 +1848,7 @@ class TestBranchMergeProposalNominateReviewer(
         votes = list(merge_proposal.votes)
         self.assertEqual(
             ['general-1', 'general-2'],
-            sorted([review.review_type for review in votes]))
+            sorted(review.review_type for review in votes))
 
     def test_nominate_multiple_with_same_types(self):
         # There can be multiple reviews for a team with the same review_type.
@@ -2111,9 +2111,9 @@ class TestBranchMergeProposalResubmit(TestCaseWithFactory):
             review_type='specious')
         bmp2 = bmp1.resubmit(bmp1.registrant)
         self.assertEqual(
-            set([(bmp1.target_branch.owner, None), (nominee, 'nominee'),
-                 (reviewer, 'specious')]),
-            set((vote.reviewer, vote.review_type) for vote in bmp2.votes))
+            {(bmp1.target_branch.owner, None), (nominee, 'nominee'),
+                 (reviewer, 'specious')},
+            {(vote.reviewer, vote.review_type) for vote in bmp2.votes})
 
     def test_resubmit_no_reviewers(self):
         """Resubmitting a proposal with no reviewers should work."""
diff --git a/lib/lp/code/model/tests/test_codeimportjob.py b/lib/lp/code/model/tests/test_codeimportjob.py
index 4ff9155..d2785a6 100644
--- a/lib/lp/code/model/tests/test_codeimportjob.py
+++ b/lib/lp/code/model/tests/test_codeimportjob.py
@@ -474,7 +474,7 @@ class NewEvents(object):
 
     def __init__(self):
         event_set = getUtility(ICodeImportEventSet)
-        self.initial = set(event.id for event in event_set.getAll())
+        self.initial = {event.id for event in event_set.getAll()}
 
     def summary(self):
         """Render a summary of the newly created CodeImportEvent objects."""
diff --git a/lib/lp/code/model/tests/test_diff.py b/lib/lp/code/model/tests/test_diff.py
index 9675214..794ffbe 100644
--- a/lib/lp/code/model/tests/test_diff.py
+++ b/lib/lp/code/model/tests/test_diff.py
@@ -282,47 +282,47 @@ class TestDiffInScripts(DiffTestCase):
         self.checkExampleBzrMerge(diff.text)
 
     diff_bytes = (
-        "--- bar\t2009-08-26 15:53:34.000000000 -0400\n"
-        "+++ bar\t1969-12-31 19:00:00.000000000 -0500\n"
-        "@@ -1,3 +0,0 @@\n"
-        "-a\n"
-        "-b\n"
-        "-c\n"
-        "--- baz\t1969-12-31 19:00:00.000000000 -0500\n"
-        "+++ baz\t2009-08-26 15:53:57.000000000 -0400\n"
-        "@@ -0,0 +1,2 @@\n"
-        "+a\n"
-        "+b\n"
-        "--- foo\t2009-08-26 15:53:23.000000000 -0400\n"
-        "+++ foo\t2009-08-26 15:56:43.000000000 -0400\n"
-        "@@ -1,3 +1,4 @@\n"
-        " a\n"
-        "-b\n"
-        " c\n"
-        "+d\n"
-        "+e\n").encode("UTF-8")
+        b"--- bar\t2009-08-26 15:53:34.000000000 -0400\n"
+        b"+++ bar\t1969-12-31 19:00:00.000000000 -0500\n"
+        b"@@ -1,3 +0,0 @@\n"
+        b"-a\n"
+        b"-b\n"
+        b"-c\n"
+        b"--- baz\t1969-12-31 19:00:00.000000000 -0500\n"
+        b"+++ baz\t2009-08-26 15:53:57.000000000 -0400\n"
+        b"@@ -0,0 +1,2 @@\n"
+        b"+a\n"
+        b"+b\n"
+        b"--- foo\t2009-08-26 15:53:23.000000000 -0400\n"
+        b"+++ foo\t2009-08-26 15:56:43.000000000 -0400\n"
+        b"@@ -1,3 +1,4 @@\n"
+        b" a\n"
+        b"-b\n"
+        b" c\n"
+        b"+d\n"
+        b"+e\n")
 
     diff_bytes_2 = (
-        "--- bar\t2009-08-26 15:53:34.000000000 -0400\n"
-        "+++ bar\t1969-12-31 19:00:00.000000000 -0500\n"
-        "@@ -1,3 +0,0 @@\n"
-        "-a\n"
-        "-b\n"
-        "-c\n"
-        "--- baz\t1969-12-31 19:00:00.000000000 -0500\n"
-        "+++ baz\t2009-08-26 15:53:57.000000000 -0400\n"
-        "@@ -0,0 +1,2 @@\n"
-        "+a\n"
-        "+b\n"
-        "--- foo\t2009-08-26 15:53:23.000000000 -0400\n"
-        "+++ foo\t2009-08-26 15:56:43.000000000 -0400\n"
-        "@@ -1,3 +1,5 @@\n"
-        " a\n"
-        "-b\n"
-        " c\n"
-        "+d\n"
-        "+e\n"
-        "+f\n").encode("UTF-8")
+        b"--- bar\t2009-08-26 15:53:34.000000000 -0400\n"
+        b"+++ bar\t1969-12-31 19:00:00.000000000 -0500\n"
+        b"@@ -1,3 +0,0 @@\n"
+        b"-a\n"
+        b"-b\n"
+        b"-c\n"
+        b"--- baz\t1969-12-31 19:00:00.000000000 -0500\n"
+        b"+++ baz\t2009-08-26 15:53:57.000000000 -0400\n"
+        b"@@ -0,0 +1,2 @@\n"
+        b"+a\n"
+        b"+b\n"
+        b"--- foo\t2009-08-26 15:53:23.000000000 -0400\n"
+        b"+++ foo\t2009-08-26 15:56:43.000000000 -0400\n"
+        b"@@ -1,3 +1,5 @@\n"
+        b" a\n"
+        b"-b\n"
+        b" c\n"
+        b"+d\n"
+        b"+e\n"
+        b"+f\n")
 
     def test_mergePreviewWithPrerequisite(self):
         # Changes introduced in the prerequisite branch are ignored.
@@ -354,10 +354,10 @@ class TestDiffInScripts(DiffTestCase):
 
     def test_generateDiffstat_with_CR(self):
         diff_bytes = (
-            "--- foo\t2009-08-26 15:53:23.000000000 -0400\n"
-            "+++ foo\t2009-08-26 15:56:43.000000000 -0400\n"
-            "@@ -1,1 +1,1 @@\n"
-            " a\r-b\r c\r+d\r+e\r+f\r").encode("UTF-8")
+            b"--- foo\t2009-08-26 15:53:23.000000000 -0400\n"
+            b"+++ foo\t2009-08-26 15:56:43.000000000 -0400\n"
+            b"@@ -1,1 +1,1 @@\n"
+            b" a\r-b\r c\r+d\r+e\r+f\r")
         self.assertEqual({'foo': (0, 0)}, Diff.generateDiffstat(diff_bytes))
 
     def test_fromFileSetsDiffstat(self):
@@ -442,7 +442,7 @@ class TestPreviewDiff(DiffTestCase):
         # canonical_url of the merge proposal itself.
         mp = self._createProposalWithPreviewDiff()
         self.assertEqual(
-            '{0}/+preview-diff/{1}'.format(
+            '{}/+preview-diff/{}'.format(
                 canonical_url(mp), mp.preview_diff.id),
             canonical_url(mp.preview_diff))
 
diff --git a/lib/lp/code/model/tests/test_gitrepository.py b/lib/lp/code/model/tests/test_gitrepository.py
index dbdf8d9..548cb62 100644
--- a/lib/lp/code/model/tests/test_gitrepository.py
+++ b/lib/lp/code/model/tests/test_gitrepository.py
@@ -1288,7 +1288,7 @@ class TestGitRepositoryModifications(TestCaseWithFactory):
         repository = self.factory.makeGitRepository(
             date_created=datetime(2015, 6, 1, tzinfo=pytz.UTC))
         [ref] = self.factory.makeGitRefs(repository=repository)
-        repository.removeRefs(set([ref.path]))
+        repository.removeRefs({ref.path})
         self.assertSqlAttributeEqualsDate(
             repository, "date_last_modified", UTC_NOW)
 
@@ -1783,7 +1783,7 @@ class TestGitRepositoryRefs(TestCaseWithFactory):
                 },
             }
         self.assertEqual(expected_upsert, refs_to_upsert)
-        self.assertEqual(set(["refs/heads/bar"]), refs_to_remove)
+        self.assertEqual({"refs/heads/bar"}, refs_to_remove)
 
     def test_planRefChanges_skips_non_commits(self):
         # planRefChanges does not attempt to update refs that point to
@@ -1957,7 +1957,7 @@ class TestGitRepositoryRefs(TestCaseWithFactory):
                 "type": GitObjectType.COMMIT,
                 },
             }
-        refs_to_remove = set(["refs/heads/bar"])
+        refs_to_remove = {"refs/heads/bar"}
         repository.synchroniseRefs(refs_to_upsert, refs_to_remove)
         expected_sha1s = [
             ("refs/heads/master", "1111111111111111111111111111111111111111"),
@@ -2968,10 +2968,10 @@ class TestGitRepositoryDetectMerges(TestCaseWithFactory):
             "Work in progress => Merged",
             notifications[0].get_payload(decode=True).decode("UTF-8"))
         self.assertEqual(proposal.address, notifications[0]["From"])
-        recipients = set(msg["x-envelope-to"] for msg in notifications)
-        expected = set(
-            [proposal.source_git_repository.registrant.preferredemail.email,
-             proposal.target_git_repository.registrant.preferredemail.email])
+        recipients = {msg["x-envelope-to"] for msg in notifications}
+        expected = {
+            proposal.source_git_repository.registrant.preferredemail.email,
+             proposal.target_git_repository.registrant.preferredemail.email}
         self.assertEqual(expected, recipients)
 
     def test_update_detects_merges(self):
@@ -3009,9 +3009,9 @@ class TestGitRepositoryDetectMerges(TestCaseWithFactory):
             expected_events, True, repository.createOrUpdateRefs, refs_info)
         expected_args = [
             (repository.getInternalPath(), target_1.commit_sha1,
-             set([source_1.commit_sha1, source_2.commit_sha1])),
+             {source_1.commit_sha1, source_2.commit_sha1}),
             (repository.getInternalPath(), target_2.commit_sha1,
-             set([source_1.commit_sha1])),
+             {source_1.commit_sha1}),
             ]
         self.assertContentEqual(
             expected_args, hosting_fixture.detectMerges.extract_args())
@@ -3027,9 +3027,9 @@ class TestGitRepositoryDetectMerges(TestCaseWithFactory):
         self.assertContentEqual(
             [(BranchMergeProposalStatus.WORK_IN_PROGRESS,
               BranchMergeProposalStatus.MERGED)],
-            set((event.object_before_modification.queue_status,
+            {(event.object_before_modification.queue_status,
                  event.object.queue_status)
-                for event in events[:2]))
+                for event in events[:2]})
 
 
 class TestGitRepositoryGetBlob(TestCaseWithFactory):
diff --git a/lib/lp/code/model/tests/test_revision.py b/lib/lp/code/model/tests/test_revision.py
index 376a32f..957f2ca 100644
--- a/lib/lp/code/model/tests/test_revision.py
+++ b/lib/lp/code/model/tests/test_revision.py
@@ -711,7 +711,7 @@ class TestOnlyPresent(TestCaseWithFactory):
         # onlyPresent returns a revid that is present in the database.
         present = self.factory.makeRevision().revision_id
         self.assertEqual(
-            set([present]),
+            {present},
             set(getUtility(IRevisionSet).onlyPresent([present])))
 
     def test_some_present(self):
@@ -719,7 +719,7 @@ class TestOnlyPresent(TestCaseWithFactory):
         not_present = self.factory.getUniqueString()
         present = self.factory.makeRevision().revision_id
         self.assertEqual(
-            set([present]),
+            {present},
             set(getUtility(IRevisionSet).onlyPresent([present, not_present])))
 
     def test_call_twice_in_one_transaction(self):
diff --git a/lib/lp/code/model/tests/test_sourcepackagerecipe.py b/lib/lp/code/model/tests/test_sourcepackagerecipe.py
index 274b1d9..719ab3b 100644
--- a/lib/lp/code/model/tests/test_sourcepackagerecipe.py
+++ b/lib/lp/code/model/tests/test_sourcepackagerecipe.py
@@ -552,7 +552,7 @@ class TestSourcePackageRecipeMixin:
         (old_distroseries,) = recipe.distroseries
         recipe.distroseries.add(distroseries)
         self.assertEqual(
-            set([distroseries, old_distroseries]), set(recipe.distroseries))
+            {distroseries, old_distroseries}, set(recipe.distroseries))
         recipe.distroseries.remove(distroseries)
         self.assertEqual([old_distroseries], list(recipe.distroseries))
         recipe.distroseries.clear()
@@ -1195,7 +1195,7 @@ class TestWebserviceMixin:
         # at the moment, distroseries is not exposed in the API.
         transaction.commit()
         db_recipe = owner.getRecipe(name='toaster-1')
-        self.assertEqual(set([db_distroseries]), set(db_recipe.distroseries))
+        self.assertEqual({db_distroseries}, set(db_recipe.distroseries))
         return recipe, ws_owner, launchpad
 
     def test_createRecipe(self):
diff --git a/lib/lp/code/tests/test_bzr.py b/lib/lp/code/tests/test_bzr.py
index 24ccead..7f6939c 100644
--- a/lib/lp/code/tests/test_bzr.py
+++ b/lib/lp/code/tests/test_bzr.py
@@ -111,11 +111,11 @@ class TestGetAncestry(TestCaseWithTransport):
         tree.commit('msg b', rev_id=b'B')
         tree.commit('msg c', rev_id=b'C')
         self.assertEqual(
-            set([b'A']), get_ancestry(branch.repository, b'A'))
+            {b'A'}, get_ancestry(branch.repository, b'A'))
         self.assertEqual(
-            set([b'A', b'B']), get_ancestry(branch.repository, b'B'))
+            {b'A', b'B'}, get_ancestry(branch.repository, b'B'))
         self.assertEqual(
-            set([b'A', b'B', b'C']), get_ancestry(branch.repository, b'C'))
+            {b'A', b'B', b'C'}, get_ancestry(branch.repository, b'C'))
 
     def test_children(self):
         # Verify non-mainline children are included.
@@ -129,8 +129,8 @@ class TestGetAncestry(TestCaseWithTransport):
         tree.set_parent_ids([b'A', b'B'])
         tree.commit('msg c', rev_id=b'C')
         self.assertEqual(
-            set([b'A']), get_ancestry(branch.repository, b'A'))
+            {b'A'}, get_ancestry(branch.repository, b'A'))
         self.assertEqual(
-            set([b'B']), get_ancestry(branch.repository, b'B'))
+            {b'B'}, get_ancestry(branch.repository, b'B'))
         self.assertEqual(
-            set([b'A', b'B', b'C']), get_ancestry(branch.repository, b'C'))
+            {b'A', b'B', b'C'}, get_ancestry(branch.repository, b'C'))
diff --git a/lib/lp/code/vocabularies/tests/test_branch_vocabularies.py b/lib/lp/code/vocabularies/tests/test_branch_vocabularies.py
index 8e0cef4..7773c17 100644
--- a/lib/lp/code/vocabularies/tests/test_branch_vocabularies.py
+++ b/lib/lp/code/vocabularies/tests/test_branch_vocabularies.py
@@ -42,7 +42,7 @@ class TestBranchVocabulary(TestCaseWithFactory):
         results = self.vocab.searchForTerms('fizzbuzz')
         expected = [
             u'~scotty/sprocket/fizzbuzz', u'~scotty/widget/fizzbuzz']
-        branch_names = sorted([branch.token for branch in results])
+        branch_names = sorted(branch.token for branch in results)
         self.assertEqual(expected, branch_names)
 
     def test_singleQueryResult(self):
@@ -99,7 +99,7 @@ class TestRestrictedBranchVocabularyOnProduct(TestCaseWithFactory):
         """
         results = self.vocab.searchForTerms('main')
         expected = [u'~scotty/widget/main']
-        branch_names = sorted([branch.token for branch in results])
+        branch_names = sorted(branch.token for branch in results)
         self.assertEqual(expected, branch_names)
 
     def test_singleQueryResult(self):
@@ -122,7 +122,7 @@ class TestRestrictedBranchVocabularyOnProduct(TestCaseWithFactory):
             self.factory.makeProductBranch(
                 owner=team, product=self.product, name='mountain')
         results = self.vocab.searchForTerms('mountain')
-        branch_names = sorted([branch.token for branch in results])
+        branch_names = sorted(branch.token for branch in results)
         self.assertEqual(['~scotty/widget/mountain'], branch_names)
 
 
diff --git a/lib/lp/code/vocabularies/tests/test_gitrepository_vocabularies.py b/lib/lp/code/vocabularies/tests/test_gitrepository_vocabularies.py
index 9d76025..774b0a1 100644
--- a/lib/lp/code/vocabularies/tests/test_gitrepository_vocabularies.py
+++ b/lib/lp/code/vocabularies/tests/test_gitrepository_vocabularies.py
@@ -40,7 +40,7 @@ class TestGitRepositoryVocabulary(TestCaseWithFactory):
         results = self.vocab.searchForTerms("fizzbuzz")
         expected = [
             u"~scotty/sprocket/+git/fizzbuzz", u"~scotty/widget/+git/fizzbuzz"]
-        repository_names = sorted([repository.token for repository in results])
+        repository_names = sorted(repository.token for repository in results)
         self.assertEqual(expected, repository_names)
 
     def test_singleQueryResult(self):
@@ -94,7 +94,7 @@ class TestRestrictedGitRepositoryVocabularyOnProduct(TestCaseWithFactory):
         """
         results = self.vocab.searchForTerms('mountain')
         expected = [u'~scotty/widget/+git/mountain']
-        repo_names = sorted([repo.token for repo in results])
+        repo_names = sorted(repo.token for repo in results)
         self.assertEqual(expected, repo_names)
 
     def test_singleQueryResult(self):
diff --git a/lib/lp/codehosting/inmemory.py b/lib/lp/codehosting/inmemory.py
index d68cc22..522f9d1 100644
--- a/lib/lp/codehosting/inmemory.py
+++ b/lib/lp/codehosting/inmemory.py
@@ -565,9 +565,9 @@ class FakeCodehosting:
                 raise UnknownBranchTypeError(
                     'Unknown branch type: %r' % (branch_type_name,))
         branches = sorted(
-            [branch for branch in self._branch_set
+            (branch for branch in self._branch_set
              if branch.next_mirror_time is not None
-             and branch.branch_type in branch_types],
+             and branch.branch_type in branch_types),
             key=operator.attrgetter('next_mirror_time'))
         if branches:
             branch = branches[-1]
@@ -655,8 +655,8 @@ class FakeCodehosting:
         # exceptions.
         if not registrant.inTeam(owner):
             raise faults.PermissionDenied(
-                ('%s cannot create branches owned by %s'
-                 % (registrant.displayname, owner.displayname)))
+                '%s cannot create branches owned by %s'
+                 % (registrant.displayname, owner.displayname))
         product = sourcepackage = None
         if data['product'] == '+junk':
             product = None
diff --git a/lib/lp/codehosting/scanner/bzrsync.py b/lib/lp/codehosting/scanner/bzrsync.py
index e4298ad..1f60b07 100755
--- a/lib/lp/codehosting/scanner/bzrsync.py
+++ b/lib/lp/codehosting/scanner/bzrsync.py
@@ -149,10 +149,10 @@ class BzrSync:
         revisions = Store.of(self.db_branch).find(Revision,
                 BranchRevision.branch_id == self.db_branch.id,
                 Revision.id == BranchRevision.revision_id)
-        parent_map = dict(
-            (six.ensure_binary(r.revision_id),
-             [six.ensure_binary(revid) for revid in r.parent_ids])
-            for r in revisions)
+        parent_map = {
+            six.ensure_binary(r.revision_id):
+             [six.ensure_binary(revid) for revid in r.parent_ids]
+            for r in revisions}
         parents_provider = DictParentsProvider(parent_map)
 
         class PPSource:
diff --git a/lib/lp/codehosting/scanner/tests/test_bzrsync.py b/lib/lp/codehosting/scanner/tests/test_bzrsync.py
index 77ef3d5..7fe8ad3 100644
--- a/lib/lp/codehosting/scanner/tests/test_bzrsync.py
+++ b/lib/lp/codehosting/scanner/tests/test_bzrsync.py
@@ -443,25 +443,25 @@ class TestBzrSync(BzrSyncTestCase):
         added_ancestry, removed_ancestry = get_delta(b'merge', None)
         # All revisions are new for an unscanned branch
         self.assertEqual(
-            set(['base', 'trunk', 'branch', 'merge']), added_ancestry)
+            {'base', 'trunk', 'branch', 'merge'}, added_ancestry)
         self.assertEqual(set(), removed_ancestry)
         added_ancestry, removed_ancestry = get_delta(b'merge', 'base')
         self.assertEqual(
-            set(['trunk', 'branch', 'merge']), added_ancestry)
+            {'trunk', 'branch', 'merge'}, added_ancestry)
         self.assertEqual(set(), removed_ancestry)
         added_ancestry, removed_ancestry = get_delta(NULL_REVISION, 'merge')
         self.assertEqual(
             set(), added_ancestry)
         self.assertEqual(
-            set(['base', 'trunk', 'branch', 'merge']), removed_ancestry)
+            {'base', 'trunk', 'branch', 'merge'}, removed_ancestry)
         added_ancestry, removed_ancestry = get_delta(b'base', 'merge')
         self.assertEqual(
             set(), added_ancestry)
         self.assertEqual(
-            set(['trunk', 'branch', 'merge']), removed_ancestry)
+            {'trunk', 'branch', 'merge'}, removed_ancestry)
         added_ancestry, removed_ancestry = get_delta(b'trunk', 'branch')
-        self.assertEqual(set(['trunk']), added_ancestry)
-        self.assertEqual(set(['branch']), removed_ancestry)
+        self.assertEqual({'trunk'}, added_ancestry)
+        self.assertEqual({'branch'}, removed_ancestry)
 
     def test_getAncestryDelta(self):
         """"Test ancestry delta calculations with a dirty repository."""
@@ -510,8 +510,8 @@ class TestBzrSync(BzrSyncTestCase):
         (db_branch, branch_tree), ignored = self.makeBranchWithMerge(
             b'r1', b'r2', b'r1.1.1', b'r3')
         self.makeBzrSync(db_branch).syncBranchAndClose()
-        expected = set(
-            [(1, 'r1'), (2, 'r2'), (3, 'r3'), (None, 'r1.1.1')])
+        expected = {
+            (1, 'r1'), (2, 'r2'), (3, 'r3'), (None, 'r1.1.1')}
         self.assertEqual(self.getBranchRevisions(db_branch), expected)
 
     def test_sync_merged_to_merging(self):
@@ -538,7 +538,7 @@ class TestBzrSync(BzrSyncTestCase):
         self.syncBazaarBranchToDatabase(trunk_tree.branch, db_trunk)
         # Then sync with the merged branch.
         self.syncBazaarBranchToDatabase(branch_tree.branch, db_trunk)
-        expected = set([(1, 'base'), (2, 'branch')])
+        expected = {(1, 'base'), (2, 'branch')}
         self.assertEqual(self.getBranchRevisions(db_trunk), expected)
 
     def test_retrieveDatabaseAncestry(self):
@@ -556,8 +556,8 @@ class TestBzrSync(BzrSyncTestCase):
         branch_revisions = IStore(BranchRevision).find(
             BranchRevision, BranchRevision.branch == branch)
         sampledata = list(branch_revisions.order_by(BranchRevision.sequence))
-        expected_ancestry = set(branch_revision.revision.revision_id
-            for branch_revision in sampledata)
+        expected_ancestry = {branch_revision.revision.revision_id
+            for branch_revision in sampledata}
         expected_history = [branch_revision.revision.revision_id
             for branch_revision in sampledata
             if branch_revision.sequence is not None]
diff --git a/lib/lp/codehosting/scanner/tests/test_mergedetection.py b/lib/lp/codehosting/scanner/tests/test_mergedetection.py
index 66c3521..4d3a93d 100644
--- a/lib/lp/codehosting/scanner/tests/test_mergedetection.py
+++ b/lib/lp/codehosting/scanner/tests/test_mergedetection.py
@@ -299,10 +299,10 @@ class TestBranchMergeDetectionHandler(TestCaseWithFactory):
             'Work in progress => Merged',
             six.ensure_text(notifications[0].get_payload(decode=True)))
         self.assertEqual(proposal.address, notifications[0]['From'])
-        recipients = set(msg['x-envelope-to'] for msg in notifications)
-        expected = set(
-            [proposal.source_branch.registrant.preferredemail.email,
-             proposal.target_branch.registrant.preferredemail.email])
+        recipients = {msg['x-envelope-to'] for msg in notifications}
+        expected = {
+            proposal.source_branch.registrant.preferredemail.email,
+             proposal.target_branch.registrant.preferredemail.email}
         self.assertEqual(expected, recipients)
 
     def test_mergeProposalMergeDetected_not_series(self):
diff --git a/lib/lp/codehosting/scripts/tests/test_modifiedbranches.py b/lib/lp/codehosting/scripts/tests/test_modifiedbranches.py
index 2d72544..6d1faf2 100644
--- a/lib/lp/codehosting/scripts/tests/test_modifiedbranches.py
+++ b/lib/lp/codehosting/scripts/tests/test_modifiedbranches.py
@@ -165,23 +165,23 @@ class TestModifiedBranchesUpdateLocations(TestCase):
     def test_single_path_element(self):
         # Adding a single element should just add that.
         self.script.update_locations('foo')
-        self.assertEqual(set(['foo']), self.script.locations)
+        self.assertEqual({'foo'}, self.script.locations)
 
     def test_single_root_element(self):
         # If the single element starts with a /, the locations do not include
         # an empty string.
         self.script.update_locations('/foo')
-        self.assertEqual(set(['/foo']), self.script.locations)
+        self.assertEqual({'/foo'}, self.script.locations)
 
     def test_multi_path_element(self):
         # Adding a "real" path will also include all the parents.
         self.script.update_locations('foo/bar/baz')
-        expected = set(['foo', 'foo/bar', 'foo/bar/baz'])
+        expected = {'foo', 'foo/bar', 'foo/bar/baz'}
         self.assertEqual(expected, self.script.locations)
 
     def test_duplicates(self):
         # Adding paths with common parentage doesn't cause duplicates.
         self.script.update_locations('foo/bar/baz')
         self.script.update_locations('foo/bar/who')
-        expected = set(['foo', 'foo/bar', 'foo/bar/baz', 'foo/bar/who'])
+        expected = {'foo', 'foo/bar', 'foo/bar/baz', 'foo/bar/who'}
         self.assertEqual(expected, self.script.locations)
diff --git a/lib/lp/codehosting/tests/test_sftp.py b/lib/lp/codehosting/tests/test_sftp.py
index 5d022dd..16df390 100644
--- a/lib/lp/codehosting/tests/test_sftp.py
+++ b/lib/lp/codehosting/tests/test_sftp.py
@@ -558,7 +558,7 @@ class TestSFTPServer(TestCaseInTempDir, SFTPTestMixin):
         names = [entry[0] for entry in entries]
         self.assertEqual(
             set(names),
-            set([child_dir.encode('UTF-8'), child_file.encode('UTF-8')]))
+            {child_dir.encode('UTF-8'), child_file.encode('UTF-8')})
 
         def check_entry(entries, filename):
             t = get_transport('.')
diff --git a/lib/lp/oci/browser/tests/test_ocirecipe.py b/lib/lp/oci/browser/tests/test_ocirecipe.py
index 4cea71a..dab70d4 100644
--- a/lib/lp/oci/browser/tests/test_ocirecipe.py
+++ b/lib/lp/oci/browser/tests/test_ocirecipe.py
@@ -1786,7 +1786,7 @@ class TestOCIRecipeRequestBuildsView(BaseTestOCIRecipeView):
             ["amd64", "i386"],
             [build.distro_arch_series.architecturetag for build in builds])
         self.assertContentEqual(
-            [2510], set(build.buildqueue_record.lastscore for build in builds))
+            [2510], {build.buildqueue_record.lastscore for build in builds})
 
     def test_request_builds_no_architectures(self):
         # Selecting no architectures causes a validation failure.
diff --git a/lib/lp/registry/browser/distributionsourcepackage.py b/lib/lp/registry/browser/distributionsourcepackage.py
index bfbbb38..48def0c 100644
--- a/lib/lp/registry/browser/distributionsourcepackage.py
+++ b/lib/lp/registry/browser/distributionsourcepackage.py
@@ -310,11 +310,11 @@ class DistributionSourcePackageBaseView(LaunchpadView):
                 [spr.changelog_entry for spr in sprs
                 if not_empty(spr.changelog_entry)])
             if self.user:
-                self._person_data = dict(
-                    [(email.email, person) for (email, person) in
+                self._person_data = {
+                    email.email: person for (email, person) in
                         getUtility(IPersonSet).getByEmails(
                             extract_email_addresses(the_changelog),
-                            include_hidden=False)])
+                            include_hidden=False)}
             else:
                 self._person_data = None
             # Collate diffs for relevant SourcePackageReleases
diff --git a/lib/lp/registry/browser/distroseries.py b/lib/lp/registry/browser/distroseries.py
index afc2290..6b162dc 100644
--- a/lib/lp/registry/browser/distroseries.py
+++ b/lib/lp/registry/browser/distroseries.py
@@ -1140,13 +1140,13 @@ class DistroSeriesDifferenceBaseView(LaunchpadFormView,
         """If specified, return Packagesets given in the GET form data."""
         packageset_ids = (
             self.request.query_string_params.get("field.packageset", []))
-        packageset_ids = set(
+        packageset_ids = {
             int(packageset_id) for packageset_id in packageset_ids
-            if packageset_id.isdigit())
+            if packageset_id.isdigit()}
         packagesets = getUtility(IPackagesetSet).getBySeries(self.context)
-        packagesets = set(
+        packagesets = {
             packageset for packageset in packagesets
-            if packageset.id in packageset_ids)
+            if packageset.id in packageset_ids}
         return None if len(packagesets) == 0 else packagesets
 
     @property
@@ -1157,8 +1157,8 @@ class DistroSeriesDifferenceBaseView(LaunchpadFormView,
             self.request.query_string_params.get("field.changed_by", ()))
         changed_by = (
             get_person_by_name(name) for name in changed_by_names)
-        changed_by = set(
-            person for person in changed_by if person is not None)
+        changed_by = {
+            person for person in changed_by if person is not None}
         return None if len(changed_by) == 0 else changed_by
 
     @property
diff --git a/lib/lp/registry/browser/milestone.py b/lib/lp/registry/browser/milestone.py
index 1a2a171..3d2724e 100644
--- a/lib/lp/registry/browser/milestone.py
+++ b/lib/lp/registry/browser/milestone.py
@@ -384,7 +384,7 @@ class MilestoneView(
 
     def getReleases(self):
         """See `ProductDownloadFileMixin`."""
-        return set([self.release])
+        return {self.release}
 
     @cachedproperty
     def download_files(self):
diff --git a/lib/lp/registry/browser/pillar.py b/lib/lp/registry/browser/pillar.py
index 4f185df..4c09eb2 100644
--- a/lib/lp/registry/browser/pillar.py
+++ b/lib/lp/registry/browser/pillar.py
@@ -221,8 +221,8 @@ class PillarInvolvementView(LaunchpadView):
     def enabled_links(self):
         """The enabled involvement links."""
         menuapi = MenuAPI(self)
-        return sorted([
-            link for link in menuapi.navigation.values() if link.enabled],
+        return sorted((
+            link for link in menuapi.navigation.values() if link.enabled),
             key=attrgetter('sort_key'))
 
     @cachedproperty
@@ -239,8 +239,8 @@ class PillarInvolvementView(LaunchpadView):
         important_links = [
             involved_menu[name]
             for name in self.visible_disabled_link_names]
-        return sorted([
-            link for link in important_links if not link.enabled],
+        return sorted((
+            link for link in important_links if not link.enabled),
             key=attrgetter('sort_key'))
 
     @property
@@ -451,7 +451,7 @@ class PillarPersonSharingView(LaunchpadView):
         self.specifications = artifacts["specifications"]
         self.ocirecipes = artifacts["ocirecipes"]
 
-        bug_ids = set([bugtask.bug.id for bugtask in self.bugtasks])
+        bug_ids = {bugtask.bug.id for bugtask in self.bugtasks}
         self.shared_bugs_count = len(bug_ids)
         self.shared_branches_count = len(self.branches)
         self.shared_gitrepositories_count = len(self.gitrepositories)
diff --git a/lib/lp/registry/browser/product.py b/lib/lp/registry/browser/product.py
index 3a853ae..942b4b9 100644
--- a/lib/lp/registry/browser/product.py
+++ b/lib/lp/registry/browser/product.py
@@ -755,7 +755,7 @@ class ProductWithSeries:
         # Get all of the releases for all of the series in a single
         # query.  The query sorts the releases properly so we know the
         # resulting list is sorted correctly.
-        series_by_id = dict((series.id, series) for series in self.series)
+        series_by_id = {series.id: series for series in self.series}
         self.release_by_id = {}
         milestones_and_releases = list(
             self.product.getMilestonesAndReleases())
@@ -1989,7 +1989,7 @@ class ProductSetBranchView(ReturnToReferrerMixin, LaunchpadFormView,
 
     def _validSchemes(self, rcs_type):
         """Return the valid schemes for the repository URL."""
-        schemes = set(['http', 'https'])
+        schemes = {'http', 'https'}
         # Extend the allowed schemes for the repository URL based on
         # rcs_type.
         extra_schemes = {
diff --git a/lib/lp/registry/browser/sourcepackage.py b/lib/lp/registry/browser/sourcepackage.py
index d5a676c..ea447c2 100644
--- a/lib/lp/registry/browser/sourcepackage.py
+++ b/lib/lp/registry/browser/sourcepackage.py
@@ -483,8 +483,8 @@ class SourcePackageView(LaunchpadView):
     def binaries(self):
         """Format binary packages into binarypackagename and archtags"""
         results = {}
-        all_arch = sorted([arch.architecturetag for arch in
-                           self.context.distroseries.architectures])
+        all_arch = sorted(arch.architecturetag for arch in
+                           self.context.distroseries.architectures)
         for bin in self.context.currentrelease.getBinariesForSeries(
                 self.context.distroseries):
             distroarchseries = bin.build.distro_arch_series
diff --git a/lib/lp/registry/browser/tests/test_mailinglists.py b/lib/lp/registry/browser/tests/test_mailinglists.py
index f9f28e9..b1154ba 100644
--- a/lib/lp/registry/browser/tests/test_mailinglists.py
+++ b/lib/lp/registry/browser/tests/test_mailinglists.py
@@ -1,4 +1,3 @@
-
 # Copyright 2010 Canonical Ltd.  This software is licensed under the
 # GNU Affero General Public License version 3 (see the file LICENSE).
 
diff --git a/lib/lp/registry/interfaces/pocket.py b/lib/lp/registry/interfaces/pocket.py
index 10443b2..47bfdc9 100644
--- a/lib/lp/registry/interfaces/pocket.py
+++ b/lib/lp/registry/interfaces/pocket.py
@@ -77,4 +77,4 @@ pocketsuffix = {
     PackagePublishingPocket.BACKPORTS: "-backports",
 }
 
-suffixpocket = dict((v, k) for (k, v) in pocketsuffix.items())
+suffixpocket = {v: k for (k, v) in pocketsuffix.items()}
diff --git a/lib/lp/registry/model/accesspolicy.py b/lib/lp/registry/model/accesspolicy.py
index ef76153..89431c7 100644
--- a/lib/lp/registry/model/accesspolicy.py
+++ b/lib/lp/registry/model/accesspolicy.py
@@ -67,7 +67,7 @@ def reconcile_access_for_artifacts(artifacts, information_type, pillars,
     abstract_artifacts = getUtility(IAccessArtifactSource).ensure(artifacts)
     aps = getUtility(IAccessPolicySource).find(
         (pillar, information_type) for pillar in pillars)
-    missing_pillars = set(pillars) - set([ap.pillar for ap in aps])
+    missing_pillars = set(pillars) - {ap.pillar for ap in aps}
     if len(missing_pillars):
         pillar_str = ', '.join([p.name for p in missing_pillars])
         raise AssertionError(
@@ -79,9 +79,9 @@ def reconcile_access_for_artifacts(artifacts, information_type, pillars,
     apasource = getUtility(IAccessPolicyArtifactSource)
     wanted_links = (
             wanted_links or set(product(abstract_artifacts, aps)))
-    existing_links = set([
+    existing_links = {
         (apa.abstract_artifact, apa.policy)
-        for apa in apasource.findByArtifact(abstract_artifacts)])
+        for apa in apasource.findByArtifact(abstract_artifacts)}
     apasource.create(wanted_links - existing_links)
     apasource.delete(existing_links - wanted_links)
 
@@ -163,7 +163,7 @@ class AccessArtifact(StormBase):
         # Not everything exists. Create missing ones.
         needed = (
             set(concrete_artifacts) -
-            set(abstract.concrete_artifact for abstract in existing))
+            {abstract.concrete_artifact for abstract in existing})
 
         insert_values = []
         for concrete in needed:
@@ -489,7 +489,7 @@ class AccessPolicyGrantFlat(StormBase):
     @classmethod
     def findGranteePermissionsByPolicy(cls, policies, grantees=None):
         """See `IAccessPolicyGrantFlatSource`."""
-        policies_by_id = dict((policy.id, policy) for policy in policies)
+        policies_by_id = {policy.id: policy for policy in policies}
 
         # A cache for the sharing permissions, keyed on grantee
         permissions_cache = defaultdict(dict)
@@ -506,8 +506,8 @@ class AccessPolicyGrantFlat(StormBase):
         def load_permissions(people):
             # We now have the grantees and policies we want in the result so
             # load any corresponding permissions and cache them.
-            people_by_id = dict(
-                (person[0].id, person[0]) for person in people)
+            people_by_id = {
+                person[0].id: person[0] for person in people}
             cls._populatePermissionsCache(
                 permissions_cache, shared_artifact_info_types,
                 people_by_id.keys(), policies_by_id, people_by_id)
diff --git a/lib/lp/registry/model/distributionsourcepackage.py b/lib/lp/registry/model/distributionsourcepackage.py
index 4606f0e..ca41f4c 100644
--- a/lib/lp/registry/model/distributionsourcepackage.py
+++ b/lib/lp/registry/model/distributionsourcepackage.py
@@ -426,9 +426,9 @@ class DistributionSourcePackage(BugTargetBase,
             sprs = [SourcePackageRelease.get(spr_id) for spr_id in spr_ids]
             pubs = DistributionSourcePackageRelease.getPublishingHistories(
                 self.distribution, sprs)
-            sprs_by_id = dict(
-                (spr, list(pubs)) for (spr, pubs) in
-                itertools.groupby(pubs, attrgetter('sourcepackagereleaseID')))
+            sprs_by_id = {
+                spr: list(pubs) for (spr, pubs) in
+                itertools.groupby(pubs, attrgetter('sourcepackagereleaseID'))}
             return [
                 (DistributionSourcePackageRelease(
                     distribution=self.distribution,
diff --git a/lib/lp/registry/model/distroseriesdifference.py b/lib/lp/registry/model/distroseriesdifference.py
index b68df3f..3845bb5 100644
--- a/lib/lp/registry/model/distroseriesdifference.py
+++ b/lib/lp/registry/model/distroseriesdifference.py
@@ -269,9 +269,9 @@ def eager_load_dsds(dsds):
             dsds, statuses=active_publishing_status,
             in_parent=True, match_version=True))
 
-    latest_comment_by_dsd_id = dict(
-        (comment.distro_series_difference_id, comment)
-        for comment in most_recent_comments(dsds))
+    latest_comment_by_dsd_id = {
+        comment.distro_series_difference_id: comment
+        for comment in most_recent_comments(dsds)}
     latest_comments = latest_comment_by_dsd_id.values()
 
     # SourcePackageReleases of the parent and source pubs are often
diff --git a/lib/lp/registry/model/person.py b/lib/lp/registry/model/person.py
index 4d0dcdc..6b3a255 100644
--- a/lib/lp/registry/model/person.py
+++ b/lib/lp/registry/model/person.py
@@ -841,10 +841,10 @@ class Person(
         # Defaults for informationalness: we don't have to do anything
         # because the default if nothing is said is ANY.
 
-        roles = set([
+        roles = {
             SpecificationFilter.CREATOR, SpecificationFilter.ASSIGNEE,
             SpecificationFilter.DRAFTER, SpecificationFilter.APPROVER,
-            SpecificationFilter.SUBSCRIBER])
+            SpecificationFilter.SUBSCRIBER}
         # If no roles are given, then we want everything.
         if filter.intersection(roles) == set():
             filter.update(roles)
@@ -2320,7 +2320,7 @@ class Person(
         # These tables will be skipped since they do not risk leaking
         # team membership information.
         # Note all of the table names and columns must be all lowercase.
-        skip = set([
+        skip = {
             ('accessartifactgrant', 'grantee'),
             ('accessartifactgrant', 'grantor'),
             ('accesspolicy', 'person'),
@@ -2380,7 +2380,7 @@ class Person(
             # user already has access to the team.
             ('latestpersonsourcepackagereleasecache', 'creator'),
             ('latestpersonsourcepackagereleasecache', 'maintainer'),
-            ])
+            }
 
         warnings = set()
         ref_query = []
@@ -2754,7 +2754,7 @@ class Person(
             AND date_consumed IS NULL
             """ % sqlvalues(self.id, LoginTokenType.VALIDATEEMAIL,
                             LoginTokenType.VALIDATETEAMEMAIL)
-        return sorted(set(token.email for token in LoginToken.select(query)))
+        return sorted({token.email for token in LoginToken.select(query)})
 
     @property
     def guessedemails(self):
@@ -2765,8 +2765,8 @@ class Person(
     def pending_gpg_keys(self):
         """See `IPerson`."""
         logintokenset = getUtility(ILoginTokenSet)
-        return sorted(set(token.fingerprint for token in
-                      logintokenset.getPendingGPGKeys(requesterid=self.id)))
+        return sorted({token.fingerprint for token in
+                      logintokenset.getPendingGPGKeys(requesterid=self.id)})
 
     @property
     def inactive_gpg_keys(self):
@@ -3848,9 +3848,9 @@ class PersonSet:
         # This has the side effect of sucking in the ValidPersonCache
         # items into the cache, allowing Person.is_valid_person calls to
         # not hit the DB.
-        valid_person_ids = set(
+        valid_person_ids = {
                 person_id.id for person_id in ValidPersonCache.select(
-                    "id IN %s" % sqlvalues(person_ids)))
+                    "id IN %s" % sqlvalues(person_ids))}
         return [
             person for person in persons if person.id in valid_person_ids]
 
diff --git a/lib/lp/registry/model/product.py b/lib/lp/registry/model/product.py
index 5956904..71e3f19 100644
--- a/lib/lp/registry/model/product.py
+++ b/lib/lp/registry/model/product.py
@@ -740,8 +740,8 @@ class Product(SQLBase, BugTargetBase, MakesAnnouncements,
         # information types.
         aps = getUtility(IAccessPolicySource)
         existing_policies = aps.findByPillar([self])
-        existing_types = set([
-            access_policy.type for access_policy in existing_policies])
+        existing_types = {
+            access_policy.type for access_policy in existing_policies}
         # Create the missing policies.
         required_types = set(information_types).difference(
             existing_types).intersection(PRIVATE_INFORMATION_TYPES)
@@ -1236,10 +1236,10 @@ class Product(SQLBase, BugTargetBase, MakesAnnouncements,
     @property
     def translatable_packages(self):
         """See `IProduct`."""
-        packages = set(
+        packages = {
             package
             for package in self.sourcepackages
-            if package.has_current_translation_templates)
+            if package.has_current_translation_templates}
 
         # Sort packages by distroseries.name and package.name
         return sorted(packages, key=lambda p: (p.distroseries.name, p.name))
@@ -1249,10 +1249,10 @@ class Product(SQLBase, BugTargetBase, MakesAnnouncements,
         """See `IProduct`."""
         if not service_uses_launchpad(self.translations_usage):
             return []
-        translatable_product_series = set(
+        translatable_product_series = {
             product_series
             for product_series in self.series
-            if product_series.has_current_translation_templates)
+            if product_series.has_current_translation_templates}
         return sorted(
             translatable_product_series,
             key=operator.attrgetter('datecreated'))
@@ -1287,9 +1287,9 @@ class Product(SQLBase, BugTargetBase, MakesAnnouncements,
     @property
     def obsolete_translatable_series(self):
         """See `IProduct`."""
-        obsolete_product_series = set(
+        obsolete_product_series = {
             product_series for product_series in self.series
-            if product_series.has_obsolete_translation_templates)
+            if product_series.has_obsolete_translation_templates}
         return sorted(obsolete_product_series, key=lambda s: s.datecreated)
 
     @property
@@ -1529,12 +1529,12 @@ def get_precached_products(products, need_licences=False,
     from lp.code.interfaces.gitrepository import IGitRepositorySet
     from lp.registry.model.projectgroup import ProjectGroup
 
-    product_ids = set(obj.id for obj in products)
+    product_ids = {obj.id for obj in products}
     if not product_ids:
         return
-    products_by_id = dict((product.id, product) for product in products)
-    caches = dict((product.id, get_property_cache(product))
-        for product in products)
+    products_by_id = {product.id: product for product in products}
+    caches = {product.id: get_property_cache(product)
+        for product in products}
     for cache in caches.values():
         if not safe_hasattr(cache, 'commercial_subscription'):
             cache.commercial_subscription = None
diff --git a/lib/lp/registry/model/sourcepackage.py b/lib/lp/registry/model/sourcepackage.py
index f27672e..1df33ee 100644
--- a/lib/lp/registry/model/sourcepackage.py
+++ b/lib/lp/registry/model/sourcepackage.py
@@ -142,7 +142,7 @@ class SourcePackageQuestionTargetMixin(QuestionTargetMixin):
             set(QuestionTargetMixin.getAnswerContactsForLanguage(
             self, language)))
         return sorted(
-            [person for person in persons], key=attrgetter('displayname'))
+            (person for person in persons), key=attrgetter('displayname'))
 
     def getAnswerContactRecipients(self, language):
         """See `IQuestionTarget`."""
@@ -761,7 +761,7 @@ class SourcePackage(BugTargetBase, HasCodeImportsMixin,
 
     def linkedBranches(self):
         """See `ISourcePackage`."""
-        return dict((p.name, b) for (p, b) in self.linked_branches)
+        return {p.name: b for (p, b) in self.linked_branches}
 
     def getBugTaskWeightFunction(self):
         """Provide a weight function to determine optimal bug task.
diff --git a/lib/lp/registry/scripts/teamparticipation.py b/lib/lp/registry/scripts/teamparticipation.py
index c332f51..cfca76a 100644
--- a/lib/lp/registry/scripts/teamparticipation.py
+++ b/lib/lp/registry/scripts/teamparticipation.py
@@ -155,7 +155,7 @@ def check_teamparticipation_consistency(log, info):
 
     log.debug("Checking consistency of %d people", len(people))
     for person in report_progress(log, 50000, people, "people"):
-        participants_expected = set((person,))
+        participants_expected = {person}
         participants_observed = team_participations[person]
         errors.extend(
             check_participants(
diff --git a/lib/lp/registry/scripts/tests/test_populate_distroseriesdiff.py b/lib/lp/registry/scripts/tests/test_populate_distroseriesdiff.py
index 9854fa7..fdd599f 100644
--- a/lib/lp/registry/scripts/tests/test_populate_distroseriesdiff.py
+++ b/lib/lp/registry/scripts/tests/test_populate_distroseriesdiff.py
@@ -143,10 +143,10 @@ class TestFindLatestSourcePackageReleases(TestCaseWithFactory, FactoryHelper):
 
     def test_does_not_find_publication_outside_primary_archive(self):
         distroseries = self.factory.makeDistroSeries()
-        spphs = dict(
-            (purpose, self.makeSPPH(
-                distroseries=distroseries, archive_purpose=purpose))
-            for purpose in ArchivePurpose.items)
+        spphs = {
+            purpose: self.makeSPPH(
+                distroseries=distroseries, archive_purpose=purpose)
+            for purpose in ArchivePurpose.items}
         query = compose_sql_find_latest_source_package_releases(distroseries)
         self.assertContentEqual(
             [self.getExpectedResultFor(spphs[ArchivePurpose.PRIMARY])],
@@ -154,9 +154,9 @@ class TestFindLatestSourcePackageReleases(TestCaseWithFactory, FactoryHelper):
 
     def test_does_not_find_publication_outside_release_pocket(self):
         distroseries = self.factory.makeDistroSeries()
-        spphs = dict(
-            (pocket, self.makeSPPH(distroseries=distroseries, pocket=pocket))
-            for pocket in PackagePublishingPocket.items)
+        spphs = {
+            pocket: self.makeSPPH(distroseries=distroseries, pocket=pocket)
+            for pocket in PackagePublishingPocket.items}
         release_spph = spphs[PackagePublishingPocket.RELEASE]
         query = compose_sql_find_latest_source_package_releases(distroseries)
         self.assertContentEqual(
@@ -165,9 +165,9 @@ class TestFindLatestSourcePackageReleases(TestCaseWithFactory, FactoryHelper):
 
     def test_finds_active_publication(self):
         distroseries = self.factory.makeDistroSeries()
-        spphs = dict(
-            (status, self.makeSPPH(distroseries=distroseries, status=status))
-            for status in active_publishing_status)
+        spphs = {
+            status: self.makeSPPH(distroseries=distroseries, status=status)
+            for status in active_publishing_status}
         query = compose_sql_find_latest_source_package_releases(distroseries)
         self.assertContentEqual(
             [self.getExpectedResultFor(spph)
diff --git a/lib/lp/registry/services/tests/test_sharingservice.py b/lib/lp/registry/services/tests/test_sharingservice.py
index 5aa3c5c..e0accd8 100644
--- a/lib/lp/registry/services/tests/test_sharingservice.py
+++ b/lib/lp/registry/services/tests/test_sharingservice.py
@@ -795,15 +795,15 @@ class TestSharingService(TestCaseWithFactory, OCIConfigHelperMixin):
         another_person_data = (
             another, {access_policies[0]: SharingPermission.ALL}, [])
         expected_data.append(another_person_data)
-        policy_permissions = dict([(
-            policy, SharingPermission.SOME) for policy in access_policies])
+        policy_permissions = {
+            policy: SharingPermission.SOME for policy in access_policies}
         yet_another_person_data = (
             yet_another, policy_permissions,
             [InformationType.PRIVATESECURITY, InformationType.USERDATA])
         expected_data.append(yet_another_person_data)
         if pillar_type == 'product':
-            policy_permissions = dict([(
-                policy, SharingPermission.ALL) for policy in access_policies])
+            policy_permissions = {
+                policy: SharingPermission.ALL for policy in access_policies}
             owner_data = (pillar.owner, policy_permissions, [])
             expected_data.append(owner_data)
         self._assert_grantee_data(
diff --git a/lib/lp/registry/tests/test_distributionmirror_prober.py b/lib/lp/registry/tests/test_distributionmirror_prober.py
index c2d89d5..0146ca4 100644
--- a/lib/lp/registry/tests/test_distributionmirror_prober.py
+++ b/lib/lp/registry/tests/test_distributionmirror_prober.py
@@ -929,7 +929,7 @@ class TestMirrorCDImageProberCallbacks(TestCaseWithFactory):
         callbacks = self.makeMirrorProberCallbacks()
         self.assertEqual(
             set(callbacks.expected_failures),
-            set([
+            {
                 BadResponseCode,
                 ProberTimeout,
                 ConnectionSkipped,
@@ -937,7 +937,7 @@ class TestMirrorCDImageProberCallbacks(TestCaseWithFactory):
                 UnknownURLSchemeAfterRedirect,
                 InvalidHTTPSCertificate,
                 InvalidHTTPSCertificateSkipped,
-                ]))
+                })
         exceptions = [BadResponseCode(http.client.NOT_FOUND),
                       ProberTimeout('http://localhost/', 5),
                       ConnectionSkipped(),
diff --git a/lib/lp/registry/tests/test_distroseries.py b/lib/lp/registry/tests/test_distroseries.py
index bb979c3..1543eca 100644
--- a/lib/lp/registry/tests/test_distroseries.py
+++ b/lib/lp/registry/tests/test_distroseries.py
@@ -660,7 +660,7 @@ class TestDistroSeriesSet(TestCaseWithFactory):
         distro_series_set = getUtility(IDistroSeriesSet)
         # Get translatables as a sequence of names of the series.
         return sorted(
-            [series.name for series in distro_series_set.translatables()])
+            series.name for series in distro_series_set.translatables())
 
     def _ref_translatables(self, expected=None):
         # Return the reference value, merged with expected data.
diff --git a/lib/lp/registry/tests/test_distroseries_vocabularies.py b/lib/lp/registry/tests/test_distroseries_vocabularies.py
index e08ea8d..c5c30b8 100644
--- a/lib/lp/registry/tests/test_distroseries_vocabularies.py
+++ b/lib/lp/registry/tests/test_distroseries_vocabularies.py
@@ -73,7 +73,7 @@ class TestDistroSeriesDerivationVocabulary(TestCaseWithFactory):
         expected_distroseries = (
             set(self.all_series_with_arch).difference(
                 distroseries.distribution.series))
-        observed_distroseries = set(term.value for term in vocabulary)
+        observed_distroseries = {term.value for term in vocabulary}
         self.assertEqual(expected_distroseries, observed_distroseries)
 
     def test_distribution_with_non_derived_series_no_arch(self):
@@ -83,7 +83,7 @@ class TestDistroSeriesDerivationVocabulary(TestCaseWithFactory):
         distroseries = self.factory.makeDistroSeries()
         vocabulary = DistroSeriesDerivationVocabulary(distroseries)
         another_parent_no_arch = self.factory.makeDistroSeries()
-        observed_distroseries = set(term.value for term in vocabulary)
+        observed_distroseries = {term.value for term in vocabulary}
 
         self.assertNotIn(another_parent_no_arch, observed_distroseries)
 
@@ -106,7 +106,7 @@ class TestDistroSeriesDerivationVocabulary(TestCaseWithFactory):
             derived_series=distroseries, parent_series=parent_distroseries)
         vocabulary = DistroSeriesDerivationVocabulary(distroseries)
         expected_distroseries = set(parent_distroseries.distribution.series)
-        observed_distroseries = set(term.value for term in vocabulary)
+        observed_distroseries = {term.value for term in vocabulary}
         self.assertContentEqual(expected_distroseries, observed_distroseries)
 
     def test_distribution_with_derived_series_no_arch(self):
@@ -119,7 +119,7 @@ class TestDistroSeriesDerivationVocabulary(TestCaseWithFactory):
         self.factory.makeDistroSeriesParent(
             derived_series=distroseries, parent_series=parent_distroseries)
         vocabulary = DistroSeriesDerivationVocabulary(distroseries)
-        observed_distroseries = set(term.value for term in vocabulary)
+        observed_distroseries = {term.value for term in vocabulary}
 
         self.assertIn(another_parent_no_arch, observed_distroseries)
 
@@ -142,7 +142,7 @@ class TestDistroSeriesDerivationVocabulary(TestCaseWithFactory):
         expected_distroseries = set(
             parent_distroseries.distribution.series).union(
                 set(another_parent_distroseries.distribution.series))
-        observed_distroseries = set(term.value for term in vocabulary)
+        observed_distroseries = {term.value for term in vocabulary}
         self.assertEqual(expected_distroseries, observed_distroseries)
 
     def test_distribution_with_derived_series_of_self(self):
@@ -159,7 +159,7 @@ class TestDistroSeriesDerivationVocabulary(TestCaseWithFactory):
         expected_distroseries = (
             set(self.all_series_with_arch).difference(
                 distroseries.distribution.series))
-        observed_distroseries = set(term.value for term in vocabulary)
+        observed_distroseries = {term.value for term in vocabulary}
         self.assertEqual(expected_distroseries, observed_distroseries)
 
     def test_distroseries(self):
@@ -170,7 +170,7 @@ class TestDistroSeriesDerivationVocabulary(TestCaseWithFactory):
         expected_distroseries = (
             set(self.all_series_with_arch).difference(
                 distroseries.distribution.series))
-        observed_distroseries = set(term.value for term in vocabulary)
+        observed_distroseries = {term.value for term in vocabulary}
         self.assertEqual(expected_distroseries, observed_distroseries)
 
     def test_ordering(self):
diff --git a/lib/lp/registry/tests/test_distroseriesdifference.py b/lib/lp/registry/tests/test_distroseriesdifference.py
index 0163383..18bb640 100644
--- a/lib/lp/registry/tests/test_distroseriesdifference.py
+++ b/lib/lp/registry/tests/test_distroseriesdifference.py
@@ -436,7 +436,7 @@ class DistroSeriesDifferenceTestCase(TestCaseWithFactory):
             ds_diff, ds_diff.parent_series, 5)
         parent_packagesets = ds_diff.parent_packagesets
         self.assertEqual(
-            sorted([packageset.name for packageset in packagesets]),
+            sorted(packageset.name for packageset in packagesets),
             [packageset.name for packageset in parent_packagesets])
 
     def test_packagesets(self):
@@ -445,7 +445,7 @@ class DistroSeriesDifferenceTestCase(TestCaseWithFactory):
         packagesets = self._setupPackageSets(
             ds_diff, ds_diff.derived_series, 5)
         self.assertEqual(
-            sorted([packageset.name for packageset in packagesets]),
+            sorted(packageset.name for packageset in packagesets),
             [packageset.name for packageset in ds_diff.packagesets])
 
     def test_blocklist_unauthorised(self):
@@ -998,17 +998,17 @@ class DistroSeriesDifferenceSourceTestCase(TestCaseWithFactory):
 
     def makeDifferencesForAllDifferenceTypes(self, derived_series):
         """Create DSDs of all types for `derived_series`."""
-        return dict(
-            (diff_type, self.factory.makeDistroSeriesDifference(
-                derived_series, difference_type=diff_type))
-            for diff_type in DistroSeriesDifferenceType.items)
+        return {
+            diff_type: self.factory.makeDistroSeriesDifference(
+                derived_series, difference_type=diff_type)
+            for diff_type in DistroSeriesDifferenceType.items}
 
     def makeDifferencesForAllStatuses(self, derived_series):
         """Create DSDs of all statuses for `derived_series`."""
-        return dict(
-            (status, self.factory.makeDistroSeriesDifference(
-                derived_series, status=status))
-            for status in DistroSeriesDifferenceStatus.items)
+        return {
+            status: self.factory.makeDistroSeriesDifference(
+                derived_series, status=status)
+            for status in DistroSeriesDifferenceStatus.items}
 
     def makeDerivedSeries(self, derived_series=None):
         """Create a derived `DistroSeries`."""
@@ -1337,9 +1337,9 @@ class TestMostRecentComments(TestCaseWithFactory):
 
     def test_most_recent_comments(self):
         dsp = self.factory.makeDistroSeriesParent()
-        dsds = set(
+        dsds = {
             self.factory.makeDistroSeriesDifference(
-                derived_series=dsp.derived_series) for index in range(5))
+                derived_series=dsp.derived_series) for index in range(5)}
         expected_comments = set()
         for dsd in dsds:
             # Add a couple of comments.
@@ -1377,9 +1377,9 @@ class TestMostRecentPublications(TestCaseWithFactory):
             self.create_difference(derived_series),
             ]
         # Derived publication.
-        source_pubs_by_spn_id_expected = set(
+        source_pubs_by_spn_id_expected = {
             (dsd.source_package_name.id, dsd.source_pub)
-            for dsd in dsds)
+            for dsd in dsds}
         source_pubs_by_spn_id_found = most_recent_publications(
             dsds, in_parent=False, statuses=(
                 PackagePublishingStatus.PUBLISHED,
@@ -1388,9 +1388,9 @@ class TestMostRecentPublications(TestCaseWithFactory):
             source_pubs_by_spn_id_expected,
             source_pubs_by_spn_id_found)
         # Parent publication
-        parent_source_pubs_by_spn_id_expected = set(
+        parent_source_pubs_by_spn_id_expected = {
             (dsd.source_package_name.id, dsd.parent_source_pub)
-            for dsd in dsds)
+            for dsd in dsds}
         parent_source_pubs_by_spn_id_found = most_recent_publications(
             dsds, in_parent=True, statuses=(
                 PackagePublishingStatus.PUBLISHED,
diff --git a/lib/lp/registry/tests/test_initderiveddistroseries.py b/lib/lp/registry/tests/test_initderiveddistroseries.py
index 07b5740..ade4a6d 100644
--- a/lib/lp/registry/tests/test_initderiveddistroseries.py
+++ b/lib/lp/registry/tests/test_initderiveddistroseries.py
@@ -84,9 +84,9 @@ class TestDeriveDistroSeriesMultipleParents(InitializationHelperTestCase):
         pub_sources = series.main_archive.getPublishedSources(
             distroseries=series)
         binaries = sorted(
-            [(p.getBuiltBinaries()[0].binarypackagerelease.sourcepackagename,
+            (p.getBuiltBinaries()[0].binarypackagerelease.sourcepackagename,
               p.getBuiltBinaries()[0].binarypackagerelease.version)
-                 for p in pub_sources])
+                 for p in pub_sources)
 
         self.assertEqual(pack_versions, binaries)
 
diff --git a/lib/lp/registry/tests/test_mailinglistapi.py b/lib/lp/registry/tests/test_mailinglistapi.py
index be9f182..c7ea028 100644
--- a/lib/lp/registry/tests/test_mailinglistapi.py
+++ b/lib/lp/registry/tests/test_mailinglistapi.py
@@ -193,9 +193,9 @@ class MailingListAPITestCase(TestCaseWithFactory):
         def getEmails(people):
             email_address_set = getUtility(IEmailAddressSet)
             return {
-                person.name: set(
+                person.name: {
                     removeSecurityProxy(email_address).email
-                    for email_address in email_address_set.getByPerson(person))
+                    for email_address in email_address_set.getByPerson(person)}
                 for person in people}
 
         self.assertThat(
diff --git a/lib/lp/registry/tests/test_milestone.py b/lib/lp/registry/tests/test_milestone.py
index 27764ab..f20894c 100644
--- a/lib/lp/registry/tests/test_milestone.py
+++ b/lib/lp/registry/tests/test_milestone.py
@@ -55,10 +55,10 @@ class MilestoneTest(unittest.TestCase):
 
     def testMilestoneSetIterator(self):
         """Test of MilestoneSet.__iter__()."""
-        all_milestones_ids = set(
-            milestone.id for milestone in getUtility(IMilestoneSet))
+        all_milestones_ids = {
+            milestone.id for milestone in getUtility(IMilestoneSet)}
         self.assertEqual(all_milestones_ids,
-                         set((1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)))
+                         {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12})
 
     def testMilestoneSetGet(self):
         """Test of MilestoneSet.get()"""
@@ -130,13 +130,13 @@ class MilestoneSecurityAdaperTestCase(TestCaseWithFactory):
             product=self.proprietary_product)
 
     expected_get_permissions = {
-        CheckerPublic: set((
+        CheckerPublic: {
             'id', 'checkAuthenticated', 'checkUnauthenticated',
             'userCanView',
-            )),
-        'launchpad.LimitedView': set((
-            'displayname', 'name', 'target',  'title',)),
-        'launchpad.View': set((
+            },
+        'launchpad.LimitedView': {
+            'displayname', 'name', 'target',  'title'},
+        'launchpad.View': {
             'active', 'bug_subscriptions', 'bugtasks', 'code_name',
             'dateexpected', 'distribution', 'distroseries',
             '_getOfficialTagClause', 'getBugSummaryContextWhereClause',
@@ -148,15 +148,15 @@ class MilestoneSecurityAdaperTestCase(TestCaseWithFactory):
             'summary', 'target_type_display', 'all_specifications',
             'userCanAlterBugSubscription', 'userCanAlterSubscription',
             'userHasBugSubscriptions',
-            )),
-        'launchpad.AnyAllowedPerson': set((
+            },
+        'launchpad.AnyAllowedPerson': {
             'addBugSubscription', 'addBugSubscriptionFilter',
             'addSubscription', 'removeBugSubscription',
-            )),
-        'launchpad.Edit': set((
+            },
+        'launchpad.Edit': {
             'closeBugsAndBlueprints', 'createProductRelease',
             'destroySelf', 'setTags',
-            )),
+            },
         }
 
     def test_get_permissions(self):
@@ -166,10 +166,10 @@ class MilestoneSecurityAdaperTestCase(TestCaseWithFactory):
             self.expected_get_permissions, checker.get_permissions, 'get')
 
     expected_set_permissions = {
-        'launchpad.Edit': set((
+        'launchpad.Edit': {
             'active', 'code_name', 'dateexpected', 'distroseries', 'name',
             'product_release', 'productseries', 'summary',
-            )),
+            },
         }
 
     def test_set_permissions(self):
@@ -640,7 +640,7 @@ class ProjectMilestoneSecurityAdaperTestCase(TestCaseWithFactory):
                 self.proprietary_projectgroup_milestone = milestone_1
 
     expected_get_permissions = {
-        'launchpad.View': set((
+        'launchpad.View': {
             '_getOfficialTagClause', 'active', 'addBugSubscription',
             'addBugSubscriptionFilter', 'addSubscription',
             'bug_subscriptions', 'bugtasks', 'closeBugsAndBlueprints',
@@ -653,7 +653,7 @@ class ProjectMilestoneSecurityAdaperTestCase(TestCaseWithFactory):
             'product_release', 'productseries', 'removeBugSubscription',
             'searchTasks', 'series_target', 'summary', 'target',
             'target_type_display', 'title', 'userCanAlterBugSubscription',
-            'userCanAlterSubscription', 'userHasBugSubscriptions')),
+            'userCanAlterSubscription', 'userHasBugSubscriptions'},
         }
 
     def test_get_permissions(self):
diff --git a/lib/lp/registry/tests/test_mlists.py b/lib/lp/registry/tests/test_mlists.py
index a581384..eedcfa2 100644
--- a/lib/lp/registry/tests/test_mlists.py
+++ b/lib/lp/registry/tests/test_mlists.py
@@ -85,7 +85,7 @@ class BaseMailingListImportTest(unittest.TestCase):
 
     def assertPeople(self, *people):
         """Assert that `people` are members of the team."""
-        members = set(person.name for person in self.team.allmembers)
+        members = {person.name for person in self.team.allmembers}
         expected = set(people)
         # Always add the team owner.
         expected.add(u'teamowner')
@@ -93,10 +93,10 @@ class BaseMailingListImportTest(unittest.TestCase):
 
     def assertAddresses(self, *addresses):
         """Assert that `addresses` are subscribed to the mailing list."""
-        subscribers = set([
+        subscribers = {
             address for (name, address) in
             getUtility(IMailingListSet).getSubscribedAddresses(
-                [self.team.name]).get(self.team.name, [])])
+                [self.team.name]).get(self.team.name, [])}
         expected = set(addresses)
         self.assertEqual(subscribers, expected)
 
@@ -469,7 +469,7 @@ class TestMailingListImportScript(BaseMailingListImportTest):
         messages = pop_notifications()
         self.assertEqual(len(messages), 5)
         # The messages are all being sent to the team owner.
-        recipients = set(message['to'] for message in messages)
+        recipients = {message['to'] for message in messages}
         self.assertEqual(len(recipients), 1)
         self.assertEqual(
             recipients.pop(),
diff --git a/lib/lp/registry/tests/test_ociproject.py b/lib/lp/registry/tests/test_ociproject.py
index 5b0924f..03036fb 100644
--- a/lib/lp/registry/tests/test_ociproject.py
+++ b/lib/lp/registry/tests/test_ociproject.py
@@ -464,8 +464,8 @@ class TestOCIProjectVocabulary(TestCaseWithFactory):
         """
         naked = removeSecurityProxy
         self.assertEqual(
-            set(naked(ociproject).id for ociproject in ociprojects),
-            set(naked(term.value).id for term in search_result))
+            {naked(ociproject).id for ociproject in ociprojects},
+            {naked(term.value).id for term in search_result})
 
     def test_search_with_name_substring(self):
         vocabulary = self.getVocabulary()
diff --git a/lib/lp/registry/tests/test_oopsreferences.py b/lib/lp/registry/tests/test_oopsreferences.py
index f06352c..175795e 100644
--- a/lib/lp/registry/tests/test_oopsreferences.py
+++ b/lib/lp/registry/tests/test_oopsreferences.py
@@ -38,7 +38,7 @@ class TestOopsReferences(TestCaseWithFactory):
         now = datetime.now(tz=utc)
         day = timedelta(days=1)
         self.assertEqual(
-            set([oopsid]),
+            {oopsid},
             referenced_oops(now - day, now, "product=1", {}))
         self.assertEqual(
             set(),
@@ -52,7 +52,7 @@ class TestOopsReferences(TestCaseWithFactory):
         now = datetime.now(tz=utc)
         day = timedelta(days=1)
         self.assertEqual(
-            set([oopsid]),
+            {oopsid},
             referenced_oops(now - day, now, "product=1", {}))
         self.assertEqual(
             set(),
@@ -67,7 +67,7 @@ class TestOopsReferences(TestCaseWithFactory):
         now = datetime.now(tz=utc)
         day = timedelta(days=1)
         self.assertEqual(
-            set([oopsid]),
+            {oopsid},
             referenced_oops(now - day, now, "product=1", {}))
         self.assertEqual(
             set(),
@@ -82,7 +82,7 @@ class TestOopsReferences(TestCaseWithFactory):
         now = datetime.now(tz=utc)
         day = timedelta(days=1)
         self.assertEqual(
-            set([oopsid]),
+            {oopsid},
             referenced_oops(now - day, now, "product=1", {}))
         self.assertEqual(
             set(),
@@ -95,11 +95,11 @@ class TestOopsReferences(TestCaseWithFactory):
         now = datetime.now(tz=utc)
         day = timedelta(days=1)
         self.assertEqual(
-            set([oopsid]),
+            {oopsid},
             referenced_oops(now - day, now, "product=%(product)s",
             {'product': question.product.id}))
         self.assertEqual(
-            set([]),
+            set(),
             referenced_oops(now + day, now + day, "product=%(product)s",
             {'product': question.product.id}))
 
@@ -123,11 +123,11 @@ class TestOopsReferences(TestCaseWithFactory):
         now = datetime.now(tz=utc)
         day = timedelta(days=1)
         self.assertEqual(
-            set([oopsid]),
+            {oopsid},
             referenced_oops(now - day, now, "product=%(product)s",
             {'product': question.product.id}))
         self.assertEqual(
-            set([]),
+            set(),
             referenced_oops(now + day, now + day, "product=%(product)s",
             {'product': question.product.id}))
 
@@ -140,11 +140,11 @@ class TestOopsReferences(TestCaseWithFactory):
         now = datetime.now(tz=utc)
         day = timedelta(days=1)
         self.assertEqual(
-            set([oopsid]),
+            {oopsid},
             referenced_oops(now - day, now, "product=%(product)s",
             {'product': question.product.id}))
         self.assertEqual(
-            set([]),
+            set(),
             referenced_oops(now + day, now + day, "product=%(product)s",
             {'product': question.product.id}))
 
@@ -158,11 +158,11 @@ class TestOopsReferences(TestCaseWithFactory):
         now = datetime.now(tz=utc)
         day = timedelta(days=1)
         self.assertEqual(
-            set([oopsid]),
+            {oopsid},
             referenced_oops(now - day, now, "distribution=%(distribution)s",
             {'distribution': distro.id}))
         self.assertEqual(
-            set([]),
+            set(),
             referenced_oops(now + day, now + day,
             "distribution=%(distribution)s", {'distribution': distro.id}))
 
@@ -187,8 +187,8 @@ class TestOopsReferences(TestCaseWithFactory):
         now = datetime.now(tz=utc)
         day = timedelta(days=1)
         self.assertEqual(
-            set([oopsid_old, oopsid_new]),
+            {oopsid_old, oopsid_new},
             referenced_oops(now - day, now, "product=1", {}))
         self.assertEqual(
-            set([]),
+            set(),
             referenced_oops(now + day, now + day, "product=1", {}))
diff --git a/lib/lp/registry/tests/test_person.py b/lib/lp/registry/tests/test_person.py
index ee75a5b..a7df518 100644
--- a/lib/lp/registry/tests/test_person.py
+++ b/lib/lp/registry/tests/test_person.py
@@ -1305,7 +1305,7 @@ class TestGetRecipients(TestCaseWithFactory):
         team = self.factory.makeTeam(owner)
         super_team = self.factory.makeTeam(team)
         recipients = get_recipients(super_team)
-        self.assertEqual(set([owner]), set(recipients))
+        self.assertEqual({owner}, set(recipients))
 
     def test_get_recipients_team(self):
         """Ensure get_recipients uses teams with preferredemail."""
@@ -1314,7 +1314,7 @@ class TestGetRecipients(TestCaseWithFactory):
         team = self.factory.makeTeam(owner, email='team@xxxxxxx')
         super_team = self.factory.makeTeam(team)
         recipients = get_recipients(super_team)
-        self.assertEqual(set([team]), set(recipients))
+        self.assertEqual({team}, set(recipients))
 
     def test_get_recipients_team_with_unvalidated_address(self):
         """Ensure get_recipients handles teams with non-preferred addresses.
@@ -1336,7 +1336,7 @@ class TestGetRecipients(TestCaseWithFactory):
     def test_get_recipients_person(self):
         person = self.factory.makePerson()
         recipients = get_recipients(person)
-        self.assertEqual(set([person]), set(recipients))
+        self.assertEqual({person}, set(recipients))
 
     def test_get_recipients_person_with_disabled_account(self):
         """Mail is not sent to a direct recipient whose account is disabled."""
@@ -1367,9 +1367,9 @@ class TestGetRecipients(TestCaseWithFactory):
         super_team_member_team.acceptInvitationToBeMemberOf(
             super_team, u'Go Team!')
         recipients = list(get_recipients(super_team))
-        self.assertEqual(set([owner,
+        self.assertEqual({owner,
                               super_team_member_person,
-                              super_team_member_team]),
+                              super_team_member_team},
                          set(recipients))
 
     def test_get_recipients_team_with_disabled_owner_account(self):
diff --git a/lib/lp/registry/tests/test_person_vocabularies.py b/lib/lp/registry/tests/test_person_vocabularies.py
index e10da4d..ea0cfcc 100644
--- a/lib/lp/registry/tests/test_person_vocabularies.py
+++ b/lib/lp/registry/tests/test_person_vocabularies.py
@@ -223,10 +223,10 @@ class TestValidPersonOrTeamPreloading(VocabularyTestBase,
 
         # Remember the current values for checking later, and throw out
         # the cache.
-        expected_nicks = dict(
-            (person.id, list(person.ircnicknames)) for person in people)
-        expected_emails = dict(
-            (person.id, person.preferredemail) for person in people)
+        expected_nicks = {
+            person.id: list(person.ircnicknames) for person in people}
+        expected_emails = {
+            person.id: person.preferredemail for person in people}
         Store.of(people[0]).invalidate()
 
         results = list(self.searchVocabulary(None, u'foobar'))
diff --git a/lib/lp/registry/tests/test_prf_finder.py b/lib/lp/registry/tests/test_prf_finder.py
index bbabb95..7b4c024 100644
--- a/lib/lp/registry/tests/test_prf_finder.py
+++ b/lib/lp/registry/tests/test_prf_finder.py
@@ -83,7 +83,7 @@ class FindReleasesDBTestCase(TestCaseWithFactory):
         self.factory.makeProductReleaseFile(
             productseries=series2, release=file2.productrelease,
             filename='foo-2.1.tar.gz')
-        expected = set(['foo-1.0.tar.gz', 'foo-2.0.tar.gz', 'foo-2.1.tar.gz'])
+        expected = {'foo-1.0.tar.gz', 'foo-2.0.tar.gz', 'foo-2.1.tar.gz'}
         transaction.commit()
         prf = ProductReleaseFinder(self.layer.txn, logging.getLogger())
         found = prf.getReleaseFileNames(product.name)
diff --git a/lib/lp/registry/tests/test_product.py b/lib/lp/registry/tests/test_product.py
index da0be15..656f7ec 100644
--- a/lib/lp/registry/tests/test_product.py
+++ b/lib/lp/registry/tests/test_product.py
@@ -339,8 +339,8 @@ class TestProduct(TestCaseWithFactory):
             licenses=[License.MIT])
         policies = getUtility(IAccessPolicySource).findByPillar((product,))
         grants = getUtility(IAccessPolicyGrantSource).findByPolicy(policies)
-        expected_grantess = set([product.owner])
-        grantees = set([grant.grantee for grant in grants])
+        expected_grantess = {product.owner}
+        grantees = {grant.grantee for grant in grants}
         self.assertEqual(expected_grantess, grantees)
 
     def test_open_product_creation_sharing_policies(self):
@@ -821,18 +821,18 @@ class TestProduct(TestCaseWithFactory):
                 product.information_type = InformationType.PROPRIETARY
 
     expected_get_permissions = {
-        CheckerPublic: set((
+        CheckerPublic: {
             'active', 'id', 'information_type', 'pillar_category', 'private',
-            'userCanLimitedView', 'userCanView',)),
-        'launchpad.LimitedView': set((
+            'userCanLimitedView', 'userCanView'},
+        'launchpad.LimitedView': {
             'bugtargetdisplayname', 'display_name', 'displayname', 'drivers',
             'enable_bug_expiration', 'getBugTaskWeightFunction',
             'getOCIProject', 'getSpecification',
             'icon', 'logo', 'name', 'official_answers', 'official_anything',
             'official_blueprints', 'official_codehosting', 'official_malone',
             'owner', 'parent_subscription_target', 'pillar', 'projectgroup',
-            'searchTasks', 'title')),
-        'launchpad.View': set((
+            'searchTasks', 'title'},
+        'launchpad.View': {
             '_getOfficialTagClause', 'visible_specifications',
             'valid_specifications', 'api_valid_specifications',
             'active_or_packaged_series', 'aliases', 'all_milestones',
@@ -894,21 +894,21 @@ class TestProduct(TestCaseWithFactory):
             'translationpermission', 'translations_usage', 'ubuntu_packages',
             'userCanAlterBugSubscription', 'userCanAlterSubscription',
             'userCanEdit', 'userHasBugSubscriptions', 'uses_launchpad',
-            'vcs', 'wikiurl')),
-        'launchpad.AnyAllowedPerson': set((
+            'vcs', 'wikiurl'},
+        'launchpad.AnyAllowedPerson': {
             'addAnswerContact', 'addBugSubscription',
             'addBugSubscriptionFilter', 'addSubscription',
             'createQuestionFromBug', 'newQuestion', 'removeAnswerContact',
-            'removeBugSubscription')),
-        'launchpad.Append': set(('newFAQ', )),
-        'launchpad.Driver': set(('newSeries', )),
-        'launchpad.Edit': set((
+            'removeBugSubscription'},
+        'launchpad.Append': {'newFAQ'},
+        'launchpad.Driver': {'newSeries'},
+        'launchpad.Edit': {
             'addOfficialBugTag', 'removeOfficialBugTag',
             'setBranchSharingPolicy', 'setBugSharingPolicy',
-            'setSpecificationSharingPolicy', 'checkInformationType')),
-        'launchpad.Moderate': set((
+            'setSpecificationSharingPolicy', 'checkInformationType'},
+        'launchpad.Moderate': {
             'is_permitted', 'license_approved', 'project_reviewed',
-            'reviewer_whiteboard', 'setAliases')),
+            'reviewer_whiteboard', 'setAliases'},
         }
 
     def test_get_permissions(self):
@@ -919,12 +919,12 @@ class TestProduct(TestCaseWithFactory):
 
     def test_set_permissions(self):
         expected_set_permissions = {
-            'launchpad.BugSupervisor': set((
+            'launchpad.BugSupervisor': {
                 'bug_reported_acknowledgement', 'bug_reporting_guidelines',
                 'bugtracker', 'enable_bug_expiration',
                 'enable_bugfiling_duplicate_search', 'official_bug_tags',
-                'official_malone', 'remote_product')),
-            'launchpad.Edit': set((
+                'official_malone', 'remote_product'},
+            'launchpad.Edit': {
                 'answers_usage', 'blueprints_usage', 'bug_supervisor',
                 'bug_tracking_usage', 'codehosting_usage',
                 'commercial_subscription', 'description', 'development_focus',
@@ -935,15 +935,15 @@ class TestProduct(TestCaseWithFactory):
                 'official_codehosting', 'owner', 'private',
                 'programminglang', 'projectgroup',
                 'releaseroot', 'screenshotsurl', 'sourceforgeproject',
-                'summary', 'uses_launchpad', 'wikiurl', 'vcs')),
-            'launchpad.Moderate': set((
+                'summary', 'uses_launchpad', 'wikiurl', 'vcs'},
+            'launchpad.Moderate': {
                 'active', 'autoupdate', 'license_approved', 'name',
-                'project_reviewed', 'registrant', 'reviewer_whiteboard')),
-            'launchpad.TranslationsAdmin': set((
+                'project_reviewed', 'registrant', 'reviewer_whiteboard'},
+            'launchpad.TranslationsAdmin': {
                 'translation_focus', 'translationgroup',
-                'translationpermission', 'translations_usage')),
-            'launchpad.AnyAllowedPerson': set((
-                'date_next_suggest_packaging', )),
+                'translationpermission', 'translations_usage'},
+            'launchpad.AnyAllowedPerson': {
+                'date_next_suggest_packaging'},
             }
         product = self.factory.makeProduct()
         checker = getChecker(product)
diff --git a/lib/lp/registry/tests/test_productseries.py b/lib/lp/registry/tests/test_productseries.py
index e833c72..52fdbcc 100644
--- a/lib/lp/registry/tests/test_productseries.py
+++ b/lib/lp/registry/tests/test_productseries.py
@@ -597,18 +597,18 @@ class ProductSeriesSecurityAdaperTestCase(TestCaseWithFactory):
             product=self.proprietary_product)
 
     expected_get_permissions = {
-        CheckerPublic: set((
+        CheckerPublic: {
             'id', 'userCanView',
-            )),
-        'launchpad.AnyAllowedPerson': set((
+            },
+        'launchpad.AnyAllowedPerson': {
             'addBugSubscription', 'addBugSubscriptionFilter',
             'addSubscription', 'removeBugSubscription',
-            )),
-        'launchpad.Edit': set(('newMilestone', )),
-        'launchpad.LimitedView': set((
+            },
+        'launchpad.Edit': {'newMilestone'},
+        'launchpad.LimitedView': {
             'bugtargetdisplayname', 'bugtarget_parent', 'name',
-            'parent_subscription_target', 'product', 'productID', 'series')),
-        'launchpad.View': set((
+            'parent_subscription_target', 'product', 'productID', 'series'},
+        'launchpad.View': {
             'visible_specifications', '_getOfficialTagClause',
             'valid_specifications', 'api_valid_specifications',
             'active', 'all_milestones', 'answers_usage', 'blueprints_usage',
@@ -644,7 +644,7 @@ class ProductSeriesSecurityAdaperTestCase(TestCaseWithFactory):
             'translations_autoimport_mode', 'userCanAlterBugSubscription',
             'userCanAlterSubscription', 'userHasBugSubscriptions',
             'translations_branch', 'translations_usage', 'uses_launchpad',
-            )),
+            },
         }
 
     def test_get_permissions(self):
@@ -653,17 +653,17 @@ class ProductSeriesSecurityAdaperTestCase(TestCaseWithFactory):
             self.expected_get_permissions, checker.get_permissions, 'get')
 
     expected_set_permissions = {
-        'launchpad.Edit': set((
+        'launchpad.Edit': {
             'answers_usage', 'blueprints_usage', 'branch',
             'bug_tracking_usage', 'codehosting_usage', 'driver', 'name',
             'owner', 'product', 'releasefileglob', 'status', 'summary',
             'translations_autoimport_mode', 'translations_branch',
             'translations_usage', 'uses_launchpad',
-            )),
-        'launchpad.AnyAllowedPerson': set((
+            },
+        'launchpad.AnyAllowedPerson': {
             'cvsbranch', 'cvsmodule', 'cvsroot', 'cvstarfileurl',
             'importstatus', 'rcstype', 'svnrepository',
-            )),
+            },
         }
 
     def test_set_permissions(self):
diff --git a/lib/lp/registry/tests/test_teammembership.py b/lib/lp/registry/tests/test_teammembership.py
index 12e45d2..520751f 100644
--- a/lib/lp/registry/tests/test_teammembership.py
+++ b/lib/lp/registry/tests/test_teammembership.py
@@ -282,7 +282,7 @@ class TeamParticipationTestCase(TestCaseWithFactory):
         """
         self.assertEqual(
             sorted(participant_names),
-            sorted([participant.name for participant in team.allmembers]))
+            sorted(participant.name for participant in team.allmembers))
 
     def getTeamParticipationCount(self):
         return IStore(TeamParticipation).find(TeamParticipation).count()
diff --git a/lib/lp/registry/vocabularies.py b/lib/lp/registry/vocabularies.py
index 9712f96..d01a9b9 100644
--- a/lib/lp/registry/vocabularies.py
+++ b/lib/lp/registry/vocabularies.py
@@ -716,9 +716,9 @@ class ValidPersonOrTeamVocabulary(
         # we get one query per person per attribute.
         def pre_iter_hook(persons):
             emails = bulk.load_referencing(EmailAddress, persons, ['personID'])
-            email_by_person = dict(
-                (email.personID, email) for email in emails
-                if email.status == EmailAddressStatus.PREFERRED)
+            email_by_person = {
+                email.personID: email for email in emails
+                if email.status == EmailAddressStatus.PREFERRED}
 
             for person in persons:
                 cache = get_property_cache(person)
@@ -1390,13 +1390,13 @@ class MilestoneVocabulary(SQLObjectVocabularyBase):
 
         # Prefetch products and distributions for rendering
         # milestones: optimization to reduce the number of queries.
-        product_ids = set(
+        product_ids = {
             removeSecurityProxy(milestone).productID
-            for milestone in milestones)
+            for milestone in milestones}
         product_ids.discard(None)
-        distro_ids = set(
+        distro_ids = {
             removeSecurityProxy(milestone).distributionID
-            for milestone in milestones)
+            for milestone in milestones}
         distro_ids.discard(None)
         if len(product_ids) > 0:
             list(Product.select("id IN %s" % sqlvalues(product_ids)))
@@ -1647,7 +1647,7 @@ class DistroSeriesDerivationVocabulary(FilteredVocabularyBase):
 
     def terms_by_token(self):
         """Mapping of terms by token."""
-        return dict((term.token, term) for term in self.terms)
+        return {term.token: term for term in self.terms}
 
     def getTermByToken(self, token):
         try:
diff --git a/lib/lp/registry/xmlrpc/canonicalsso.py b/lib/lp/registry/xmlrpc/canonicalsso.py
index 9abfdf5..d3e398f 100644
--- a/lib/lp/registry/xmlrpc/canonicalsso.py
+++ b/lib/lp/registry/xmlrpc/canonicalsso.py
@@ -37,9 +37,9 @@ class CanonicalSSOAPI(LaunchpadXMLRPCView):
             return
 
         time_zone = person.time_zone
-        team_names = dict(
-            (removeSecurityProxy(t).name, t.private)
-            for t in person.teams_participated_in)
+        team_names = {
+            removeSecurityProxy(t).name: t.private
+            for t in person.teams_participated_in}
         return {
             'name': person.name,
             'time_zone': time_zone,
diff --git a/lib/lp/scripts/garbo.py b/lib/lp/scripts/garbo.py
index e2471dc..f744715 100644
--- a/lib/lp/scripts/garbo.py
+++ b/lib/lp/scripts/garbo.py
@@ -1396,7 +1396,7 @@ class UnusedPOTMsgSetPruner(TunableLoop):
             """ % constraints
         store = IMasterStore(POTMsgSet)
         results = store.execute(query)
-        ids_to_remove = set([id for (id,) in results.get_all()])
+        ids_to_remove = {id for (id,) in results.get_all()}
         return list(ids_to_remove)
 
     def __call__(self, chunk_size):
diff --git a/lib/lp/scripts/tests/test_garbo.py b/lib/lp/scripts/tests/test_garbo.py
index a700663..f976bdb 100644
--- a/lib/lp/scripts/tests/test_garbo.py
+++ b/lib/lp/scripts/tests/test_garbo.py
@@ -346,14 +346,14 @@ class TestSessionPruner(TestCase):
         finally:
             pruner.cleanUp()
 
-        expected_sessions = set([
+        expected_sessions = {
             'recent_auth',
             'recent_unauth',
             'yesterday_auth',
             'yesterday_unauth',
             # 'ancient_auth',
             # 'ancient_unauth',
-            ])
+            }
 
         found_sessions = set(
             IMasterStore(SessionData).find(SessionData.client_id))
@@ -369,14 +369,14 @@ class TestSessionPruner(TestCase):
         finally:
             pruner.cleanUp()
 
-        expected_sessions = set([
+        expected_sessions = {
             'recent_auth',
             'recent_unauth',
             'yesterday_auth',
             # 'yesterday_unauth',
             'ancient_auth',
             # 'ancient_unauth',
-            ])
+            }
 
         found_sessions = set(
             IMasterStore(SessionData).find(SessionData.client_id))
@@ -386,14 +386,14 @@ class TestSessionPruner(TestCase):
     def test_duplicate_session_pruner(self):
         # None of the sessions created in setUp() are duplicates, so
         # they will all survive the pruning.
-        expected_sessions = set([
+        expected_sessions = {
             'recent_auth',
             'recent_unauth',
             'yesterday_auth',
             'yesterday_unauth',
             'ancient_auth',
             'ancient_unauth',
-            ])
+            }
 
         now = datetime.now(UTC)
 
diff --git a/lib/lp/scripts/utilities/importpedant.py b/lib/lp/scripts/utilities/importpedant.py
index 695f647..03c5ebd 100644
--- a/lib/lp/scripts/utilities/importpedant.py
+++ b/lib/lp/scripts/utilities/importpedant.py
@@ -22,22 +22,22 @@ naughty_imports = set()
 # __all__. The following dict maps from such modules to a list of attributes
 # that are allowed to be imported, whether or not they are in __all__.
 valid_imports_not_in_all = {
-    'importlib': set(['resources']),
-    'openid.fetchers': set(['Urllib2Fetcher']),
-    'openid.message': set(['NamespaceAliasRegistrationError']),
-    'six.moves.http_cookiejar': set(['domain_match']),
-    'storm.database': set(['STATE_DISCONNECTED']),
-    'talisker': set(['run_gunicorn']),
-    'textwrap': set(['dedent']),
-    'testtools.testresult.real': set(['_details_to_str']),
-    'twisted.internet.threads': set(['deferToThreadPool']),
+    'importlib': {'resources'},
+    'openid.fetchers': {'Urllib2Fetcher'},
+    'openid.message': {'NamespaceAliasRegistrationError'},
+    'six.moves.http_cookiejar': {'domain_match'},
+    'storm.database': {'STATE_DISCONNECTED'},
+    'talisker': {'run_gunicorn'},
+    'textwrap': {'dedent'},
+    'testtools.testresult.real': {'_details_to_str'},
+    'twisted.internet.threads': {'deferToThreadPool'},
     # Even docs tell us to use this class. See docs on WebClientContextFactory.
-    'twisted.web.client': set(['BrowserLikePolicyForHTTPS']),
-    'zope.component': set(
-        ['adapter',
+    'twisted.web.client': {'BrowserLikePolicyForHTTPS'},
+    'zope.component': {
+        'adapter',
          'provideAdapter',
          'provideHandler',
-         ]),
+         },
     # https://github.com/zopefoundation/zope.interface/pull/248
     'zope.interface.interfaces': {
         'ComponentLookupError',
@@ -49,7 +49,7 @@ valid_imports_not_in_all = {
     }
 
 
-unsafe_parts = set(['browser', 'feed', 'xmlrpc', 'widgets'])
+unsafe_parts = {'browser', 'feed', 'xmlrpc', 'widgets'}
 
 dubious = [
     'lp.answers.browser.question',
@@ -308,7 +308,7 @@ def report_naughty_imports():
                 sorted_violations, attrsgetter('name', 'attrname')):
                 print("You should not import %s from %s:" % (attrname, name))
                 import_intos = sorted(
-                    set([error.import_into for error in sequence]))
+                    {error.import_into for error in sequence})
                 for import_into in import_intos:
                     print("   ", import_into)
 
diff --git a/lib/lp/scripts/utilities/warninghandler.py b/lib/lp/scripts/utilities/warninghandler.py
index 0c9aea3..ec847c7 100644
--- a/lib/lp/scripts/utilities/warninghandler.py
+++ b/lib/lp/scripts/utilities/warninghandler.py
@@ -70,13 +70,13 @@ class ImportantInfo:
 def find_important_info():
     stack = inspect.stack()
     try:
-        important_classes = set([
+        important_classes = {
             PythonExpr,
             TrustedZopeContext,
             TALInterpreter,
             ViewPageTemplateFile,
             simple
-            ])
+            }
         important_objects = {}
         metadata = {}  # cls -> (filename, lineno, funcname)
 
diff --git a/lib/lp/security.py b/lib/lp/security.py
index 0c871fc..8f66fbb 100644
--- a/lib/lp/security.py
+++ b/lib/lp/security.py
@@ -1087,10 +1087,10 @@ class PublicOrPrivateTeamsExistence(AuthorizationBase):
             # team's private PPA.
             subscriptions = getUtility(
                 IArchiveSubscriberSet).getBySubscriber(user.person)
-            subscriber_archive_ids = set(
-                sub.archive_id for sub in subscriptions)
-            team_ppa_ids = set(
-                ppa.id for ppa in self.obj.ppas if ppa.private)
+            subscriber_archive_ids = {
+                sub.archive_id for sub in subscriptions}
+            team_ppa_ids = {
+                ppa.id for ppa in self.obj.ppas if ppa.private}
             if len(subscriber_archive_ids.intersection(team_ppa_ids)) > 0:
                 return True
 
diff --git a/lib/lp/services/config/tests/test_config.py b/lib/lp/services/config/tests/test_config.py
index 61e90a6..4161eb8 100644
--- a/lib/lp/services/config/tests/test_config.py
+++ b/lib/lp/services/config/tests/test_config.py
@@ -63,7 +63,7 @@ class TestLaunchpadConfig(testtools.TestCase):
         names = set(dir(config))
         self.assertTrue(names.issuperset(dir(config.__class__)))
         self.assertTrue(names.issuperset(config.__dict__))
-        section_names = set(section.name for section in config._config)
+        section_names = {section.name for section in config._config}
         self.assertTrue(names.issuperset(section_names))
 
     def test_iter(self):
diff --git a/lib/lp/services/database/bulk.py b/lib/lp/services/database/bulk.py
index c6bd72f..517e522 100644
--- a/lib/lp/services/database/bulk.py
+++ b/lib/lp/services/database/bulk.py
@@ -240,7 +240,7 @@ def create(columns, values, get_objects=False,
     """
     # Flatten Reference faux-columns into their primary keys.
     db_cols = list(chain.from_iterable(map(dbify_column, columns)))
-    clses = set(col.cls for col in db_cols)
+    clses = {col.cls for col in db_cols}
     if len(clses) != 1:
         raise ValueError(
             "The Storm columns to insert values into must be from a single "
diff --git a/lib/lp/services/database/postgresql.py b/lib/lp/services/database/postgresql.py
index 9d3faaf..6dba9d0 100644
--- a/lib/lp/services/database/postgresql.py
+++ b/lib/lp/services/database/postgresql.py
@@ -516,9 +516,9 @@ def all_tables_in_schema(cur, schema):
             AND pg_namespace.nspname = %s
             AND pg_class.relkind = 'r'
         """ % sqlvalues(schema))
-    return set(
+    return {
             fqn(namespace, tablename)
-            for namespace, tablename in cur.fetchall())
+            for namespace, tablename in cur.fetchall()}
 
 
 def all_sequences_in_schema(cur, schema):
@@ -534,9 +534,9 @@ def all_sequences_in_schema(cur, schema):
             AND pg_namespace.nspname = %s
             AND pg_class.relkind = 'S'
         """ % sqlvalues(schema))
-    return set(
+    return {
             fqn(namespace, sequence)
-            for namespace, sequence in cur.fetchall())
+            for namespace, sequence in cur.fetchall()}
 
 
 def fqn(namespace, name):
diff --git a/lib/lp/services/database/sqlbase.py b/lib/lp/services/database/sqlbase.py
index 0d3f51d..43cd316 100644
--- a/lib/lp/services/database/sqlbase.py
+++ b/lib/lp/services/database/sqlbase.py
@@ -408,7 +408,7 @@ def sqlvalues(*values, **kwvalues):
     if values:
         return tuple(quote(item) for item in values)
     elif kwvalues:
-        return dict((key, quote(value)) for key, value in kwvalues.items())
+        return {key: quote(value) for key, value in kwvalues.items()}
 
 
 def quote_identifier(identifier):
diff --git a/lib/lp/services/database/tests/test_bulk.py b/lib/lp/services/database/tests/test_bulk.py
index aa3a30c..03cb64d 100644
--- a/lib/lp/services/database/tests/test_bulk.py
+++ b/lib/lp/services/database/tests/test_bulk.py
@@ -100,8 +100,8 @@ class TestLoaders(TestCaseWithFactory):
     def test_gen_reload_queries_with_multiple_similar_objects(self):
         # gen_reload_queries() should generate a single query to load
         # multiple objects of the same type.
-        db_objects = set(
-            self.factory.makeSourcePackageName() for i in range(5))
+        db_objects = {
+            self.factory.makeSourcePackageName() for i in range(5)}
         db_queries = list(bulk.gen_reload_queries(db_objects))
         self.assertEqual(1, len(db_queries))
         db_query = db_queries[0]
@@ -110,8 +110,8 @@ class TestLoaders(TestCaseWithFactory):
     def test_gen_reload_queries_with_mixed_objects(self):
         # gen_reload_queries() should return one query for each
         # distinct object type in the given objects.
-        db_objects = set(
-            self.factory.makeSourcePackageName() for i in range(5))
+        db_objects = {
+            self.factory.makeSourcePackageName() for i in range(5)}
         db_objects.update(
             self.factory.makeComponent() for i in range(5))
         db_queries = list(bulk.gen_reload_queries(db_objects))
@@ -254,7 +254,7 @@ class TestLoaders(TestCaseWithFactory):
             self.factory.makeBug(),
             self.factory.makeBug(),
             ]
-        expected = set(bug.owner for bug in owning_objects)
+        expected = {bug.owner for bug in owning_objects}
         self.assertEqual(expected,
             set(bulk.load_related(Person, owning_objects, ['ownerID'])))
 
diff --git a/lib/lp/services/database/tests/test_connectionstring.py b/lib/lp/services/database/tests/test_connectionstring.py
index 957478d..1af7205 100644
--- a/lib/lp/services/database/tests/test_connectionstring.py
+++ b/lib/lp/services/database/tests/test_connectionstring.py
@@ -48,4 +48,4 @@ class TestConnectionString(TestCase):
         self.assertNotEqual(cs2, cs3)
         self.assertEqual(hash(cs1), hash(cs2))
         self.assertNotEqual(hash(cs1), hash(cs3))
-        self.assertContentEqual([cs1, cs3], set([cs1, cs2, cs3]))
+        self.assertContentEqual([cs1, cs3], {cs1, cs2, cs3})
diff --git a/lib/lp/services/features/flags.py b/lib/lp/services/features/flags.py
index a53cc0f..87f0f7d 100644
--- a/lib/lp/services/features/flags.py
+++ b/lib/lp/services/features/flags.py
@@ -233,7 +233,7 @@ flag_info = sorted([
     ])
 
 # The set of all flag names that are documented.
-documented_flags = set(info[0] for info in flag_info)
+documented_flags = {info[0] for info in flag_info}
 # The set of all the flags names that have been used during the process
 # lifetime, but were not documented in flag_info.
 undocumented_flags = set()
@@ -386,7 +386,7 @@ class FeatureController():
         or a few flags.
         """
         self._needRules()
-        return dict((f, self.getFlag(f)) for f in self._rules)
+        return {f: self.getFlag(f) for f in self._rules}
 
     def _needRules(self):
         if self._rules is None:
diff --git a/lib/lp/services/features/scopes.py b/lib/lp/services/features/scopes.py
index bebae27..3d7f3ca 100644
--- a/lib/lp/services/features/scopes.py
+++ b/lib/lp/services/features/scopes.py
@@ -233,7 +233,7 @@ class FixedScope(BaseScope):
 # we can for example show all of them in an admin page.  Any new scope will
 # need a scope handler and that scope handler has to be added to this list.
 # See BaseScope for hints as to what a scope handler should look like.
-HANDLERS = set([DefaultScope, PageScope, TeamScope, ServerScope, ScriptScope])
+HANDLERS = {DefaultScope, PageScope, TeamScope, ServerScope, ScriptScope}
 
 
 class MultiScopeHandler():
diff --git a/lib/lp/services/gpg/tests/test_gpghandler.py b/lib/lp/services/gpg/tests/test_gpghandler.py
index fe0f5d8..5b023ba 100644
--- a/lib/lp/services/gpg/tests/test_gpghandler.py
+++ b/lib/lp/services/gpg/tests/test_gpghandler.py
@@ -125,8 +125,8 @@ class TestGPGHandler(TestCase):
         self.populateKeyring()
 
         self.assertNotEqual([], list(self.gpg_handler.localKeys()))
-        fingerprints = set(key.fingerprint
-                           for key in self.gpg_handler.localKeys())
+        fingerprints = {key.fingerprint
+                           for key in self.gpg_handler.localKeys()}
         self.assertTrue("340CA3BB270E2716C9EE0B768E7EB7086C64A8C5"
                         in fingerprints)
         self.assertTrue("A419AE861E88BC9E04B9C26FBA2B9389DFD20543"
@@ -276,7 +276,7 @@ class TestGPGHandler(TestCase):
         gpghandler = getUtility(IGPGHandler)
         self.assertEqual(
             fingerprint, gpghandler.retrieveKey(key_id).fingerprint)
-        fingerprints = set(key.fingerprint for key in gpghandler.localKeys())
+        fingerprints = {key.fingerprint for key in gpghandler.localKeys()}
         self.assertIn(fingerprint, fingerprints)
 
     def test_retrieveKey_checks_64bit_key_id(self):
diff --git a/lib/lp/services/job/celeryjob.py b/lib/lp/services/job/celeryjob.py
index 0d949de..c872bf8 100644
--- a/lib/lp/services/job/celeryjob.py
+++ b/lib/lp/services/job/celeryjob.py
@@ -89,8 +89,8 @@ class FindMissingReady:
         from lazr.jobrunner.celerytask import list_queued
         self.job_source = job_source
         self.queue_contents = list_queued(celery_app, [job_source.task_queue])
-        self.queued_job_ids = set(task[1][0][0] for task in
-                                  self.queue_contents)
+        self.queued_job_ids = {task[1][0][0] for task in
+                                  self.queue_contents}
 
     def find_missing_ready(self):
         return [job for job in self.job_source.iterReady()
diff --git a/lib/lp/services/librarianserver/librariangc.py b/lib/lp/services/librarianserver/librariangc.py
index 9f0f09c..3779dca 100644
--- a/lib/lp/services/librarianserver/librariangc.py
+++ b/lib/lp/services/librarianserver/librariangc.py
@@ -891,13 +891,13 @@ def delete_unwanted_swift_files(con):
         if os.path.exists(path) and (os.stat(path).st_ctime
                                      < time() - (7 * 24 * 60 * 60)):
             log.error(
-                "LibraryFileContent {0} exists in the database and disk "
+                "LibraryFileContent {} exists in the database and disk "
                 "but was not found in Swift.".format(next_wanted_content_id))
         next_wanted_content_id = get_next_wanted_content_id()
 
     cur.close()
     log.info(
-        "Deleted {0} files from Swift that were no longer referenced "
+        "Deleted {} files from Swift that were no longer referenced "
         "in the db.".format(removed_count))
 
 
diff --git a/lib/lp/services/librarianserver/swift.py b/lib/lp/services/librarianserver/swift.py
index 1602cd3..d844d50 100644
--- a/lib/lp/services/librarianserver/swift.py
+++ b/lib/lp/services/librarianserver/swift.py
@@ -76,10 +76,10 @@ def to_swift(log, start_lfc_id=None, end_lfc_id=None,
         # Maximum id capable of being stored on the filesystem - ffffffff
         end_lfc_id = 0xffffffff
 
-    log.info("Walking disk store {0} from {1} to {2}, inclusive".format(
+    log.info("Walking disk store {} from {} to {}, inclusive".format(
         fs_root, start_lfc_id, end_lfc_id))
     if instance_id is not None and num_instances is not None:
-        log.info("Parallel mode: instance ID {0} of {1}".format(
+        log.info("Parallel mode: instance ID {} of {}".format(
             instance_id, num_instances))
 
     start_fs_path = filesystem_path(start_lfc_id)
@@ -101,7 +101,7 @@ def to_swift(log, start_lfc_id=None, end_lfc_id=None,
             # an aborted job.
             dirnames.sort()
 
-        log.debug('Scanning {0} for matching files'.format(dirpath))
+        log.debug('Scanning {} for matching files'.format(dirpath))
 
         _filename_re = re.compile('^[0-9a-f]{2}$')
 
@@ -131,22 +131,22 @@ def to_swift(log, start_lfc_id=None, end_lfc_id=None,
             hex_lfc = ''.join(rel_fs_path.split('/'))
             if len(hex_lfc) != 8:
                 log.warning(
-                    'Filename length fail, skipping {0}'.format(fs_path))
+                    'Filename length fail, skipping {}'.format(fs_path))
                 continue
             try:
                 lfc = int(hex_lfc, 16)
             except ValueError:
-                log.warning('Invalid hex fail, skipping {0}'.format(fs_path))
+                log.warning('Invalid hex fail, skipping {}'.format(fs_path))
                 continue
             if instance_id is not None and num_instances is not None:
                 if (lfc % num_instances) != instance_id:
                     continue
 
-            log.debug('Found {0} ({1})'.format(lfc, filename))
+            log.debug('Found {} ({})'.format(lfc, filename))
 
             if ISlaveStore(LibraryFileContent).get(
                     LibraryFileContent, lfc) is None:
-                log.info("{0} exists on disk but not in the db".format(
+                log.info("{} exists on disk but not in the db".format(
                     lfc))
                 continue
 
@@ -169,28 +169,28 @@ def _to_swift_file(log, swift_connection, lfc_id, fs_path):
 
     try:
         quiet_swiftclient(swift_connection.head_container, container)
-        log.debug2('{0} container already exists'.format(container))
+        log.debug2('{} container already exists'.format(container))
     except swiftclient.ClientException as x:
         if x.http_status != 404:
             raise
-        log.info('Creating {0} container'.format(container))
+        log.info('Creating {} container'.format(container))
         swift_connection.put_container(container)
 
     try:
         headers = quiet_swiftclient(
             swift_connection.head_object, container, obj_name)
         log.debug(
-            "{0} already exists in Swift({1}, {2})".format(
+            "{} already exists in Swift({}, {})".format(
                 lfc_id, container, obj_name))
         if ('X-Object-Manifest' not in headers and
                 int(headers['content-length'])
                 != os.path.getsize(fs_path)):
             raise AssertionError(
-                '{0} has incorrect size in Swift'.format(lfc_id))
+                '{} has incorrect size in Swift'.format(lfc_id))
     except swiftclient.ClientException as x:
         if x.http_status != 404:
             raise
-        log.info('Putting {0} into Swift ({1}, {2})'.format(
+        log.info('Putting {} into Swift ({}, {})'.format(
             lfc_id, container, obj_name))
         _put(log, swift_connection, lfc_id, container, obj_name, fs_path)
 
@@ -219,8 +219,8 @@ def _put(log, swift_connection, lfc_id, container, obj_name, fs_path):
         disk_md5_hash = fs_file.hash.hexdigest()
         if not (disk_md5_hash == db_md5_hash == swift_md5_hash):
             log.error(
-                "LibraryFileContent({0}) corrupt. "
-                "disk md5={1}, db md5={2}, swift md5={3}".format(
+                "LibraryFileContent({}) corrupt. "
+                "disk md5={}, db md5={}, swift md5={}".format(
                     lfc_id, disk_md5_hash, db_md5_hash, swift_md5_hash))
             try:
                 swift_connection.delete_object(container, obj_name)
@@ -241,7 +241,7 @@ def _put(log, swift_connection, lfc_id, container, obj_name, fs_path):
                 container, seg_name, md5_stream, seg_size)
             segment_md5_hash = md5_stream.hash.hexdigest()
             assert swift_md5_hash == segment_md5_hash, (
-                "LibraryFileContent({0}) segment {1} upload corrupted".format(
+                "LibraryFileContent({}) segment {} upload corrupted".format(
                     lfc_id, segment))
             segment = segment + 1
 
@@ -250,12 +250,12 @@ def _put(log, swift_connection, lfc_id, container, obj_name, fs_path):
             # We don't have to delete the uploaded segments, as Librarian
             # Garbage Collection handles this for us.
             log.error(
-                "Large LibraryFileContent({0}) corrupt. "
-                "disk md5={1}, db_md5={2}".format(
+                "Large LibraryFileContent({}) corrupt. "
+                "disk md5={}, db_md5={}".format(
                     lfc_id, disk_md5_hash, db_md5_hash))
             raise AssertionError('md5 mismatch')
 
-        manifest = '{0}/{1}/'.format(quote(container), quote(obj_name))
+        manifest = '{}/{}/'.format(quote(container), quote(obj_name))
         manifest_headers = {'X-Object-Manifest': manifest}
         swift_connection.put_object(
             container, obj_name, b'', 0, headers=manifest_headers)
diff --git a/lib/lp/services/librarianserver/tests/test_gc.py b/lib/lp/services/librarianserver/tests/test_gc.py
index ca2e57e..30dbf3a 100644
--- a/lib/lp/services/librarianserver/tests/test_gc.py
+++ b/lib/lp/services/librarianserver/tests/test_gc.py
@@ -99,7 +99,7 @@ class TestLibrarianGarbageCollectionBase:
             if not os.path.exists(path):
                 if not os.path.exists(os.path.dirname(path)):
                     os.makedirs(os.path.dirname(path))
-                content_bytes = '{0} content'.format(content.id).encode(
+                content_bytes = '{} content'.format(content.id).encode(
                     'UTF-8')
                 with open(path, 'wb') as f:
                     f.write(content_bytes)
diff --git a/lib/lp/services/librarianserver/tests/test_swift.py b/lib/lp/services/librarianserver/tests/test_swift.py
index cbc65ce..98595b6 100644
--- a/lib/lp/services/librarianserver/tests/test_swift.py
+++ b/lib/lp/services/librarianserver/tests/test_swift.py
@@ -51,7 +51,7 @@ class TestFeedSwift(TestCase):
         self.librarian_client = LibrarianClient()
         self.contents = [str(i).encode('ASCII') * i for i in range(1, 5)]
         self.lfa_ids = [
-            self.add_file('file_{0}'.format(i), content, when=the_past)
+            self.add_file('file_{}'.format(i), content, when=the_past)
             for i, content in enumerate(self.contents)]
         self.lfas = [
             IStore(LibraryFileAlias).get(LibraryFileAlias, lfa_id)
@@ -312,12 +312,12 @@ class TestFeedSwift(TestCase):
         self.assertEqual(obj, b'')
 
         # The segments we expect are all in their expected locations.
-        _, obj1 = swift_client.get_object(container, '{0}/0000'.format(name))
-        _, obj2 = swift_client.get_object(container, '{0}/0001'.format(name))
-        _, obj3 = swift_client.get_object(container, '{0}/0002'.format(name))
+        _, obj1 = swift_client.get_object(container, '{}/0000'.format(name))
+        _, obj2 = swift_client.get_object(container, '{}/0001'.format(name))
+        _, obj3 = swift_client.get_object(container, '{}/0002'.format(name))
         self.assertRaises(
             swiftclient.ClientException, swift.quiet_swiftclient,
-            swift_client.get_object, container, '{0}/0003'.format(name))
+            swift_client.get_object, container, '{}/0003'.format(name))
 
         # Our object round tripped
         self.assertEqual(obj1 + obj2 + obj3, expected_content)
diff --git a/lib/lp/services/log/logger.py b/lib/lp/services/log/logger.py
index 2976112..848ff0c 100644
--- a/lib/lp/services/log/logger.py
+++ b/lib/lp/services/log/logger.py
@@ -20,9 +20,9 @@ import six
 from lp.services.log import loglevels
 
 
-LEVEL_PREFIXES = dict(
-    (debug_level, "DEBUG%d" % (1 + debug_level - loglevels.DEBUG))
-    for debug_level in range(loglevels.DEBUG9, loglevels.DEBUG))
+LEVEL_PREFIXES = {
+    debug_level: "DEBUG%d" % (1 + debug_level - loglevels.DEBUG)
+    for debug_level in range(loglevels.DEBUG9, loglevels.DEBUG)}
 
 LEVEL_PREFIXES.update({
     loglevels.DEBUG: 'DEBUG',
diff --git a/lib/lp/services/mail/commands.py b/lib/lp/services/mail/commands.py
index c3ad171..038f8b4 100644
--- a/lib/lp/services/mail/commands.py
+++ b/lib/lp/services/mail/commands.py
@@ -143,9 +143,9 @@ class EmailCommandCollection:
     @classmethod
     def parsingParameters(klass):
         """Returns all the command names."""
-        return dict(
-            (command_name, command.case_insensitive_args)
-            for command_name, command in klass._commands.items())
+        return {
+            command_name: command.case_insensitive_args
+            for command_name, command in klass._commands.items()}
 
     @classmethod
     def get(klass, name, string_args):
diff --git a/lib/lp/services/mail/helpers.py b/lib/lp/services/mail/helpers.py
index c156e75..207efb7 100644
--- a/lib/lp/services/mail/helpers.py
+++ b/lib/lp/services/mail/helpers.py
@@ -281,6 +281,6 @@ def get_contact_email_addresses(person):
 
     # Circular imports force this import.
     from lp.registry.model.person import get_recipients
-    return set(
+    return {
         str(removeSecurityProxy(mail_person).preferredemail.email)
-        for mail_person in get_recipients(person))
+        for mail_person in get_recipients(person)}
diff --git a/lib/lp/services/mail/tests/test_helpers.py b/lib/lp/services/mail/tests/test_helpers.py
index dc0775c..a15d804 100644
--- a/lib/lp/services/mail/tests/test_helpers.py
+++ b/lib/lp/services/mail/tests/test_helpers.py
@@ -267,13 +267,13 @@ class Testget_contact_email_addresses(TestCaseWithFactory):
             hide_email_addresses=True,
             name='user')
         result = get_contact_email_addresses(user)
-        self.assertEqual(set(['user@xxxxxxxxxxxxx']), result)
+        self.assertEqual({'user@xxxxxxxxxxxxx'}, result)
 
     def test_user_with_preferredemail(self):
         user = self.factory.makePerson(
             email='user@xxxxxxxxxxxxx', name='user',)
         result = get_contact_email_addresses(user)
-        self.assertEqual(set(['user@xxxxxxxxxxxxx']), result)
+        self.assertEqual({'user@xxxxxxxxxxxxx'}, result)
 
     def test_private_team(self):
         email = 'team@xxxxxxxxxxxxx'
@@ -282,7 +282,7 @@ class Testget_contact_email_addresses(TestCaseWithFactory):
             email=email,
             visibility=PersonVisibility.PRIVATE)
         result = get_contact_email_addresses(team)
-        self.assertEqual(set(['team@xxxxxxxxxxxxx']), result)
+        self.assertEqual({'team@xxxxxxxxxxxxx'}, result)
 
 
 def test_suite():
diff --git a/lib/lp/services/messages/tests/test_message.py b/lib/lp/services/messages/tests/test_message.py
index a1769b0..9828dd3 100644
--- a/lib/lp/services/messages/tests/test_message.py
+++ b/lib/lp/services/messages/tests/test_message.py
@@ -279,7 +279,7 @@ class TestMessageEditing(MessageTypeScenariosMixin, TestCaseWithFactory):
         # new text message.
         self.assertEqual(3, len(msg.chunks))
         # Make sure we avoid gaps in sequence.
-        self.assertEqual([1, 2, 3], sorted([i.sequence for i in msg.chunks]))
+        self.assertEqual([1, 2, 3], sorted(i.sequence for i in msg.chunks))
         self.assertThat(msg.chunks[0], MatchesStructure(
             content=Equals("final form"),
             sequence=Equals(1),
diff --git a/lib/lp/services/messaging/tests/test_rabbit.py b/lib/lp/services/messaging/tests/test_rabbit.py
index 717991d..8666638 100644
--- a/lib/lp/services/messaging/tests/test_rabbit.py
+++ b/lib/lp/services/messaging/tests/test_rabbit.py
@@ -395,9 +395,9 @@ class TestRabbit(RabbitTestCase):
         except KeyError:
             return set()
         else:
-            return set(
+            return {
                 sync.session for sync in six.itervalues(syncs_set.data)
-                if isinstance(sync, RabbitSessionTransactionSync))
+                if isinstance(sync, RabbitSessionTransactionSync)}
 
     def test_global_session(self):
         self.assertIsInstance(global_session, RabbitSession)
diff --git a/lib/lp/services/oauth/browser/__init__.py b/lib/lp/services/oauth/browser/__init__.py
index 99296d5..b0b5bb9 100644
--- a/lib/lp/services/oauth/browser/__init__.py
+++ b/lib/lp/services/oauth/browser/__init__.py
@@ -231,10 +231,10 @@ class OAuthAuthorizeTokenView(LaunchpadFormView, JSONTokenMixin):
                 # they give a desktop type (eg. "Ubuntu") and a
                 # user-recognizable desktop name (eg. the hostname).
                 raise Unauthorized(
-                    ('Consumer "%s" asked for desktop integration, '
+                    'Consumer "%s" asked for desktop integration, '
                      "but didn't say what kind of desktop it is, or name "
                      "the computer being integrated."
-                     % self.token.consumer.key))
+                     % self.token.consumer.key)
 
             # We're going for desktop integration. There are four
             # possibilities: "allow permanently", "allow for one
diff --git a/lib/lp/services/profile/mem.py b/lib/lp/services/profile/mem.py
index 9aeaca1..5862809 100644
--- a/lib/lp/services/profile/mem.py
+++ b/lib/lp/services/profile/mem.py
@@ -154,8 +154,8 @@ def countsByType(objects, n=30):
 
 def deltaCounts(counts1, counts2, n=30):
     """Compare two references counts lists and return the increase."""
-    counts1_map = dict((ref_type, count) for count, ref_type in counts1)
-    counts2_map = dict((ref_type, count) for count, ref_type in counts2)
+    counts1_map = {ref_type: count for count, ref_type in counts1}
+    counts2_map = {ref_type: count for count, ref_type in counts2}
     types1 = set(counts1_map.keys())
     types2 = set(counts2_map.keys())
     delta = []
diff --git a/lib/lp/services/profile/profile.py b/lib/lp/services/profile/profile.py
index a7a0352..cce5f39 100644
--- a/lib/lp/services/profile/profile.py
+++ b/lib/lp/services/profile/profile.py
@@ -300,7 +300,7 @@ def end_request(event):
         _major, _minor, content_type_params = parse(content_type)
         is_html = _major == 'text' and _minor == 'html'
     template_context = {
-        'actions': dict((key, True) for key in actions),
+        'actions': {key: True for key in actions},
         'always_log': config.profiling.profile_all_requests}
     dump_path = config.profiling.profile_dir
     if _profilers.profiler is not None:
@@ -542,7 +542,7 @@ def get_desired_profile_actions(request):
             elif 'sql' in result:
                 result['sql'] = False
             # Only honor the available options.
-            available_options = set(('show', 'sql', 'help'))
+            available_options = {'show', 'sql', 'help'}
             available_options.update(available_profilers)
             # .keys() gives a list, not mutated during iteration.
             for key in result.keys():
diff --git a/lib/lp/services/profile/tests.py b/lib/lp/services/profile/tests.py
index 3ba84ea..1b41785 100644
--- a/lib/lp/services/profile/tests.py
+++ b/lib/lp/services/profile/tests.py
@@ -207,7 +207,7 @@ class TestRequestStartHandler(TestCleanupProfiler):
         self.pushProfilingConfig(profiling_allowed='True')
         profile.start_request(self._get_start_event('/++profile++show/'))
         self.assertIsInstance(profile._profilers.profiler, profile.Profiler)
-        self.assertEqual(set(profile._profilers.actions), set(('show', )))
+        self.assertEqual(set(profile._profilers.actions), {'show'})
 
     def test_optional_profiling_with_callgrind_request_starts_profiling(self):
         # If profiling is allowed and a request with the "callgrind" marker
@@ -216,7 +216,7 @@ class TestRequestStartHandler(TestCleanupProfiler):
         profile.start_request(self._get_start_event('/++profile++callgrind/'))
         self.assertIsInstance(profile._profilers.profiler, profile.Profiler)
         self.assertEqual(
-            set(profile._profilers.actions), set(('callgrind', )))
+            set(profile._profilers.actions), {'callgrind'})
 
     def test_optional_profiling_with_log_request_starts_profiling(self):
         # If profiling is allowed and a request with the "log" marker URL
@@ -225,7 +225,7 @@ class TestRequestStartHandler(TestCleanupProfiler):
         profile.start_request(self._get_start_event('/++profile++log/'))
         self.assertIsInstance(profile._profilers.profiler, profile.Profiler)
         self.assertEqual(
-            set(profile._profilers.actions), set(('callgrind', )))
+            set(profile._profilers.actions), {'callgrind'})
 
     def test_optional_profiling_with_combined_request_starts_profiling(self):
         # If profiling is allowed and a request with the "callgrind" and
@@ -235,7 +235,7 @@ class TestRequestStartHandler(TestCleanupProfiler):
             self._get_start_event('/++profile++callgrind&show/'))
         self.assertIsInstance(profile._profilers.profiler, profile.Profiler)
         self.assertEqual(
-            set(profile._profilers.actions), set(('callgrind', 'show')))
+            set(profile._profilers.actions), {'callgrind', 'show'})
 
     def test_optional_profiling_with_reversed_request_starts_profiling(self):
         # If profiling is allowed and a request with the "show" and the
@@ -248,7 +248,7 @@ class TestRequestStartHandler(TestCleanupProfiler):
             self._get_start_event('/++profile++show&callgrind'))
         self.assertIsInstance(profile._profilers.profiler, profile.Profiler)
         self.assertEqual(
-            set(profile._profilers.actions), set(('callgrind', 'show')))
+            set(profile._profilers.actions), {'callgrind', 'show'})
 
     def test_optional_profiling_with_pstats_request_starts_profiling(self):
         # If profiling is allowed and a request with the "pstats" marker,
@@ -258,7 +258,7 @@ class TestRequestStartHandler(TestCleanupProfiler):
             self._get_start_event('/++profile++pstats/'))
         self.assertIsInstance(profile._profilers.profiler,
                               profile.Profiler)
-        self.assertEqual(set(profile._profilers.actions), set(('pstats',)))
+        self.assertEqual(set(profile._profilers.actions), {'pstats'})
 
     def test_optional_profiling_with_log_pstats(self):
         # If profiling is allowed and a request with the "log" and "pstats"
@@ -269,7 +269,7 @@ class TestRequestStartHandler(TestCleanupProfiler):
             self._get_start_event('/++profile++log&pstats/'))
         self.assertIsInstance(profile._profilers.profiler, profile.Profiler)
         self.assertEqual(
-            set(profile._profilers.actions), set(('callgrind', 'pstats',)))
+            set(profile._profilers.actions), {'callgrind', 'pstats'})
 
     def test_optional_profiling_with_callgrind_pstats(self):
         # If profiling is allowed and a request with both the "pstats" and
@@ -281,7 +281,7 @@ class TestRequestStartHandler(TestCleanupProfiler):
         self.assertIsInstance(profile._profilers.profiler,
                               profile.Profiler)
         self.assertEqual(
-            set(profile._profilers.actions), set(('pstats', 'callgrind')))
+            set(profile._profilers.actions), {'pstats', 'callgrind'})
 
     def test_forced_profiling_registers_action(self):
         # profile_all_requests should register as a callgrind action.
@@ -290,7 +290,7 @@ class TestRequestStartHandler(TestCleanupProfiler):
         profile.start_request(self._get_start_event('/'))
         self.assertIsInstance(profile._profilers.profiler, profile.Profiler)
         self.assertEqual(
-            set(profile._profilers.actions), set(('callgrind', )))
+            set(profile._profilers.actions), {'callgrind'})
 
     def test_optional_profiling_with_wrong_request_helps(self):
         # If profiling is allowed and a request with the marker URL segment
@@ -298,7 +298,7 @@ class TestRequestStartHandler(TestCleanupProfiler):
         self.pushProfilingConfig(profiling_allowed='True')
         profile.start_request(self._get_start_event('/++profile++/'))
         self.assertIs(getattr(profile._profilers, 'profiler', None), None)
-        self.assertEqual(set(profile._profilers.actions), set(('help', )))
+        self.assertEqual(set(profile._profilers.actions), {'help'})
 
     def test_forced_profiling_with_wrong_request_helps(self):
         # If profiling is forced and a request with the marker URL segment
@@ -308,7 +308,7 @@ class TestRequestStartHandler(TestCleanupProfiler):
         profile.start_request(self._get_start_event('/++profile++/'))
         self.assertIsInstance(profile._profilers.profiler, profile.Profiler)
         self.assertEqual(
-            set(profile._profilers.actions), set(('help', 'callgrind')))
+            set(profile._profilers.actions), {'help', 'callgrind'})
 
     def test_memory_profile_start(self):
         self.pushProfilingConfig(
@@ -316,7 +316,7 @@ class TestRequestStartHandler(TestCleanupProfiler):
         profile.start_request(self._get_start_event('/'))
         self.assertIs(getattr(profile._profilers, 'profiler', None), None)
         actions = profile._profilers.actions
-        self.assertEqual(set(actions), set(['memory_profile_start']))
+        self.assertEqual(set(actions), {'memory_profile_start'})
         self.assertIsInstance(actions['memory_profile_start'], tuple)
         self.assertEqual(len(actions['memory_profile_start']), 2)
 
@@ -326,7 +326,7 @@ class TestRequestStartHandler(TestCleanupProfiler):
         profile.start_request(self._get_start_event('/++profile++show/'))
         self.assertIsInstance(profile._profilers.profiler, profile.Profiler)
         actions = profile._profilers.actions
-        self.assertEqual(set(actions), set(['memory_profile_start', 'show']))
+        self.assertEqual(set(actions), {'memory_profile_start', 'show'})
         self.assertIsInstance(actions['memory_profile_start'], tuple)
         self.assertEqual(len(actions['memory_profile_start']), 2)
 
@@ -349,7 +349,7 @@ class TestRequestStartHandler(TestCleanupProfiler):
         profile.start_request(self._get_start_event(
             '/++profile++sqltrace:includes bugsubscription/'))
         self.assertIs(getattr(profile._profilers, 'profiler', None), None)
-        self.assertEqual(set(profile._profilers.actions), set(('sql', )))
+        self.assertEqual(set(profile._profilers.actions), {'sql'})
         data = profile._profilers.actions['sql']
         self.assertTrue(data['condition']('SELECT BUGSUBSCRIPTION FROM FOO'))
         self.assertEqual([], da.stop_sql_logging())
@@ -695,7 +695,7 @@ class TestBeforeTraverseHandler(TestCleanupProfiler):
             self.assertIsInstance(
                 profile._profilers.profiler, profile.Profiler)
             self.assertEqual(
-                set(('show', 'callgrind', 'memory_profile_start')),
+                {'show', 'callgrind', 'memory_profile_start'},
                 set(profile._profilers.actions))
 
 
diff --git a/lib/lp/services/twistedsupport/features.py b/lib/lp/services/twistedsupport/features.py
index d56f398..300976c 100644
--- a/lib/lp/services/twistedsupport/features.py
+++ b/lib/lp/services/twistedsupport/features.py
@@ -55,14 +55,14 @@ def _install_and_reschedule(controller, script_name):
     try:
         refresh = float(refresh)
     except ValueError:
-        log.msg("Invalid value {0!r} for twisted.flags.refresh".format(
+        log.msg("Invalid value {!r} for twisted.flags.refresh".format(
             refresh))
         refresh = 60.0
 
     global _last_refresh
     if refresh != _last_refresh:
         if _last_refresh is not None:
-            log.msg("twisted.flags.refresh changed to {0}".format(refresh))
+            log.msg("twisted.flags.refresh changed to {}".format(refresh))
         _last_refresh = refresh
 
     reactor.callLater(refresh, update, script_name)
diff --git a/lib/lp/services/utils.py b/lib/lp/services/utils.py
index 0f6e1b6..2de70b1 100644
--- a/lib/lp/services/utils.py
+++ b/lib/lp/services/utils.py
@@ -316,9 +316,9 @@ def obfuscate_structure(o):
     elif isinstance(o, (list, tuple)):
         return [obfuscate_structure(value) for value in o]
     elif isinstance(o, (dict)):
-        return dict(
-            (obfuscate_structure(key), obfuscate_structure(value))
-            for key, value in six.iteritems(o))
+        return {
+            obfuscate_structure(key): obfuscate_structure(value)
+            for key, value in six.iteritems(o)}
     else:
         return o
 
diff --git a/lib/lp/services/webapp/batching.py b/lib/lp/services/webapp/batching.py
index 8f403cc..6f0707e 100644
--- a/lib/lp/services/webapp/batching.py
+++ b/lib/lp/services/webapp/batching.py
@@ -52,8 +52,8 @@ from lp.services.webapp.publisher import LaunchpadView
 def get_batch_properties_for_json_cache(view, batchnav):
     """Get values to insert into `IJSONRequestCache` for JS batchnavs."""
     properties = {}
-    view_names = set(
-        reg.name for reg in iter_view_registrations(view.__class__))
+    view_names = {
+        reg.name for reg in iter_view_registrations(view.__class__)}
     if len(view_names) != 1:
         raise AssertionError("Ambiguous view name.")
     properties['view_name'] = view_names.pop()
diff --git a/lib/lp/services/webapp/errorlog.py b/lib/lp/services/webapp/errorlog.py
index a6838bd..f7a83fe 100644
--- a/lib/lp/services/webapp/errorlog.py
+++ b/lib/lp/services/webapp/errorlog.py
@@ -122,7 +122,7 @@ def attach_exc_info(report, context):
     report['tb_text'] = tb_text
 
 
-_ignored_exceptions_for_unauthenticated_users = set(['Unauthorized'])
+_ignored_exceptions_for_unauthenticated_users = {'Unauthorized'}
 
 
 def attach_previous_oopsid(report, context):
@@ -259,9 +259,9 @@ def _get_type(report):
 @implementer(IErrorReportingUtility)
 class ErrorReportingUtility:
 
-    _ignored_exceptions = set(['TranslationUnavailable', 'NoReferrerError'])
-    _ignored_exceptions_for_offsite_referer = set([
-        'GoneError', 'InvalidBatchSizeError', 'NotFound'])
+    _ignored_exceptions = {'TranslationUnavailable', 'NoReferrerError'}
+    _ignored_exceptions_for_offsite_referer = {
+        'GoneError', 'InvalidBatchSizeError', 'NotFound'}
     _default_config_section = 'error_reports'
 
     def __init__(self):
diff --git a/lib/lp/services/webapp/escaping.py b/lib/lp/services/webapp/escaping.py
index 244df3f..1e1c502 100644
--- a/lib/lp/services/webapp/escaping.py
+++ b/lib/lp/services/webapp/escaping.py
@@ -102,8 +102,8 @@ class structured:
         if reps:
             self.escapedtext = text % tuple(html_escape(rep) for rep in reps)
         elif kwreps:
-            self.escapedtext = text % dict(
-                (k, html_escape(v)) for k, v in six.iteritems(kwreps))
+            self.escapedtext = text % {
+                k: html_escape(v) for k, v in six.iteritems(kwreps)}
         else:
             self.escapedtext = text
 
diff --git a/lib/lp/services/webapp/menu.py b/lib/lp/services/webapp/menu.py
index f5599db..7ebdd4b 100644
--- a/lib/lp/services/webapp/menu.py
+++ b/lib/lp/services/webapp/menu.py
@@ -197,9 +197,9 @@ class MenuBase(UserAttributeCache):
     enable_only = ALL_LINKS
     _baseclassname = 'MenuBase'
     _initialized = False
-    _forbiddenlinknames = set(
-        ['user', 'initialize', 'links', 'enable_only', 'iterlinks',
-         'initLink', 'updateLink', 'extra_attributes'])
+    _forbiddenlinknames = {
+        'user', 'initialize', 'links', 'enable_only', 'iterlinks',
+         'initLink', 'updateLink', 'extra_attributes'}
 
     def __init__(self, context):
         # The attribute self.context is defined in IMenuBase.
diff --git a/lib/lp/services/webapp/tests/test_error.py b/lib/lp/services/webapp/tests/test_error.py
index 1293f94..3a360f0 100644
--- a/lib/lp/services/webapp/tests/test_error.py
+++ b/lib/lp/services/webapp/tests/test_error.py
@@ -116,7 +116,7 @@ class TestDatabaseErrorViews(TestCase):
         else:
             self.add_retry_failure_details(bouncer)
             raise TimeoutException(
-                "Launchpad did not come up after {0} attempts."
+                "Launchpad did not come up after {} attempts."
                     .format(retries))
 
     def test_disconnectionerror_view_integration(self):
diff --git a/lib/lp/services/webapp/tests/test_errorlog.py b/lib/lp/services/webapp/tests/test_errorlog.py
index 587f18f..7fb92f4 100644
--- a/lib/lp/services/webapp/tests/test_errorlog.py
+++ b/lib/lp/services/webapp/tests/test_errorlog.py
@@ -389,9 +389,9 @@ class TestErrorReportingUtility(TestCaseWithFactory):
         # Exceptions caused by bad URLs that may not be an Lp code issue.
         utility = ErrorReportingUtility()
         utility._oops_config.publisher = None
-        errors = set([
+        errors = {
             GoneError.__name__, InvalidBatchSizeError.__name__,
-            NotFound.__name__])
+            NotFound.__name__}
         self.assertEqual(
             errors, utility._ignored_exceptions_for_offsite_referer)
 
diff --git a/lib/lp/services/webhooks/model.py b/lib/lp/services/webhooks/model.py
index 82005ab..435bca8 100644
--- a/lib/lp/services/webhooks/model.py
+++ b/lib/lp/services/webhooks/model.py
@@ -228,7 +228,7 @@ class WebhookSet:
         hooks = list(hooks)
         getUtility(IWebhookJobSource).deleteByWebhooks(hooks)
         IStore(Webhook).find(
-            Webhook, Webhook.id.is_in(set(hook.id for hook in hooks))).remove()
+            Webhook, Webhook.id.is_in({hook.id for hook in hooks})).remove()
 
     def getByID(self, id):
         return IStore(Webhook).get(Webhook, id)
diff --git a/lib/lp/services/webhooks/tests/test_model.py b/lib/lp/services/webhooks/tests/test_model.py
index 62e42b4..5fce64d 100644
--- a/lib/lp/services/webhooks/tests/test_model.py
+++ b/lib/lp/services/webhooks/tests/test_model.py
@@ -107,11 +107,11 @@ class TestWebhookPermissions(TestCaseWithFactory):
 
     def test_get_permissions(self):
         expected_get_permissions = {
-            'launchpad.View': set((
+            'launchpad.View': {
                 'active', 'date_created', 'date_last_modified', 'deliveries',
                 'delivery_url', 'destroySelf', 'event_types', 'getDelivery',
                 'id', 'ping', 'registrant', 'registrant_id', 'secret',
-                'setSecret', 'target')),
+                'setSecret', 'target'},
             }
         webhook = self.factory.makeWebhook()
         checker = getChecker(webhook)
@@ -120,9 +120,9 @@ class TestWebhookPermissions(TestCaseWithFactory):
 
     def test_set_permissions(self):
         expected_set_permissions = {
-            'launchpad.View': set((
+            'launchpad.View': {
                 'active', 'delivery_url', 'event_types', 'registrant_id',
-                'secret')),
+                'secret'},
             }
         webhook = self.factory.makeWebhook()
         checker = getChecker(webhook)
diff --git a/lib/lp/services/worlddata/model/language.py b/lib/lp/services/worlddata/model/language.py
index ba9cf55..aef4e0e 100644
--- a/lib/lp/services/worlddata/model/language.py
+++ b/lib/lp/services/worlddata/model/language.py
@@ -222,8 +222,8 @@ class LanguageSet:
         if want_translators_count:
             def preload_translators_count(languages):
                 from lp.registry.model.person import PersonLanguage
-                ids = set(language.id for language in languages).difference(
-                    set([None]))
+                ids = {language.id for language in languages}.difference(
+                    {None})
                 counts = IStore(Language).using(
                     LeftJoin(
                         Language,
diff --git a/lib/lp/snappy/tests/test_snapstoreclient.py b/lib/lp/snappy/tests/test_snapstoreclient.py
index 7aa3f62..66e446b 100644
--- a/lib/lp/snappy/tests/test_snapstoreclient.py
+++ b/lib/lp/snappy/tests/test_snapstoreclient.py
@@ -227,7 +227,7 @@ class TestSnapStoreClient(TestCaseWithFactory):
             {"name": "stable", "display_name": "Stable"},
             {"name": "edge", "display_name": "Edge"},
             ]
-        self.channels_memcache_key = "search.example:channels".encode("UTF-8")
+        self.channels_memcache_key = b"search.example:channels"
 
     def _make_store_secrets(self, encrypted=False):
         self.root_key = hashlib.sha256(
diff --git a/lib/lp/snappy/vocabularies.py b/lib/lp/snappy/vocabularies.py
index 0d2d13e..6fa31a9 100644
--- a/lib/lp/snappy/vocabularies.py
+++ b/lib/lp/snappy/vocabularies.py
@@ -234,7 +234,7 @@ class SnapStoreChannelVocabulary(SimpleVocabulary):
             # used by this context.
             context_channels = removeSecurityProxy(context)._store_channels
             if context_channels is not None:
-                known_names = set(channel["name"] for channel in channels)
+                known_names = {channel["name"] for channel in channels}
                 for name in context_channels:
                     if name not in known_names:
                         terms.append(self.createTerm(name, name, name))
diff --git a/lib/lp/soyuz/adapters/archivedependencies.py b/lib/lp/soyuz/adapters/archivedependencies.py
index 27ae3e3..20643b6 100644
--- a/lib/lp/soyuz/adapters/archivedependencies.py
+++ b/lib/lp/soyuz/adapters/archivedependencies.py
@@ -393,10 +393,10 @@ def _get_sources_list_for_dependencies(behaviour, dependencies, logger=None):
                 archive, distro_arch_series, pocket)
             if not has_published_binaries:
                 continue
-            archive_components = set(
+            archive_components = {
                 component.name
                 for component in archive.getComponentsForSeries(
-                    distro_arch_series.distroseries))
+                    distro_arch_series.distroseries)}
             components = [
                 component for component in components
                 if component in archive_components]
diff --git a/lib/lp/soyuz/adapters/buildarch.py b/lib/lp/soyuz/adapters/buildarch.py
index b1da6ae..982305a 100644
--- a/lib/lp/soyuz/adapters/buildarch.py
+++ b/lib/lp/soyuz/adapters/buildarch.py
@@ -53,7 +53,7 @@ dpkg_architecture = DpkgArchitectureCache()
 def resolve_arch_spec(hintlist, valid_archs):
     hint_archs = set(hintlist.split())
     # 'all' is only used if it's a purely arch-indep package.
-    if hint_archs == set(["all"]):
+    if hint_archs == {"all"}:
         return set(), True
     return (
         set(dpkg_architecture.findAllMatches(valid_archs, hint_archs)), False)
diff --git a/lib/lp/soyuz/adapters/copypolicy.py b/lib/lp/soyuz/adapters/copypolicy.py
index a1c6867..3b11921 100644
--- a/lib/lp/soyuz/adapters/copypolicy.py
+++ b/lib/lp/soyuz/adapters/copypolicy.py
@@ -85,7 +85,7 @@ policies = [
     ]
 
 
-enum_to_policy = dict((policy.enum_value, policy()) for policy in policies)
+enum_to_policy = {policy.enum_value: policy() for policy in policies}
 
 
 def get_icopypolicy_for_packagecopypolicy(packagecopypolicy):
diff --git a/lib/lp/soyuz/adapters/overrides.py b/lib/lp/soyuz/adapters/overrides.py
index 8d34b62..3f93f64 100644
--- a/lib/lp/soyuz/adapters/overrides.py
+++ b/lib/lp/soyuz/adapters/overrides.py
@@ -270,12 +270,12 @@ class FromExistingOverridePolicy(BaseOverridePolicy):
                         SourcePackagePublishingHistory.sourcepackagenameID,)),
             id_resolver((SourcePackageName, Component, Section, None, None)),
             pre_iter_hook=eager_load)
-        return dict(
-            (name, SourceOverride(
+        return {
+            name: SourceOverride(
                 component=component, section=section, version=version,
-                new=(status == PackagePublishingStatus.DELETED)))
+                new=(status == PackagePublishingStatus.DELETED))
             for (name, component, section, status, version)
-            in already_published)
+            in already_published}
 
     def calculateBinaryOverrides(self, binaries):
         def eager_load(rows):
@@ -348,7 +348,7 @@ class FromExistingOverridePolicy(BaseOverridePolicy):
                     matching_keys.append((name, None))
             else:
                 matching_keys = [
-                    (name, archtag) for archtag in archtags | set((None,))]
+                    (name, archtag) for archtag in archtags | {None}]
             for key in matching_keys:
                 if key not in binaries:
                     continue
@@ -416,20 +416,20 @@ class UnknownOverridePolicy(BaseOverridePolicy):
             return override_component_name
 
     def calculateSourceOverrides(self, sources):
-        return dict(
-            (spn, SourceOverride(
+        return {
+            spn: SourceOverride(
                 component=UnknownOverridePolicy.getComponentOverride(
                     override.component, return_component=True),
-                new=True))
-            for spn, override in sources.items())
+                new=True)
+            for spn, override in sources.items()}
 
     def calculateBinaryOverrides(self, binaries):
         default_component = getUtility(IComponentSet)['universe']
-        return dict(
-            ((binary_package_name, architecture_tag), BinaryOverride(
+        return {
+            (binary_package_name, architecture_tag): BinaryOverride(
                 component=default_component, new=True,
-                phased_update_percentage=self.phased_update_percentage))
-            for binary_package_name, architecture_tag in binaries.keys())
+                phased_update_percentage=self.phased_update_percentage)
+            for binary_package_name, architecture_tag in binaries.keys()}
 
 
 class ConstantOverridePolicy(BaseOverridePolicy):
@@ -444,18 +444,18 @@ class ConstantOverridePolicy(BaseOverridePolicy):
         self.new = new
 
     def calculateSourceOverrides(self, sources):
-        return dict(
-            (key, SourceOverride(
+        return {
+            key: SourceOverride(
                 component=self.component, section=self.section,
-                new=self.new)) for key in sources.keys())
+                new=self.new) for key in sources.keys()}
 
     def calculateBinaryOverrides(self, binaries):
-        return dict(
-            (key, BinaryOverride(
+        return {
+            key: BinaryOverride(
                 component=self.component, section=self.section,
                 priority=self.priority,
                 phased_update_percentage=self.phased_update_percentage,
-                new=self.new)) for key in binaries.keys())
+                new=self.new) for key in binaries.keys()}
 
 
 class FallbackOverridePolicy(BaseOverridePolicy):
@@ -471,7 +471,7 @@ class FallbackOverridePolicy(BaseOverridePolicy):
             if not missing:
                 break
             these_overrides = policy.calculateSourceOverrides(
-                dict((spn, sources[spn]) for spn in missing))
+                {spn: sources[spn] for spn in missing})
             overrides.update(these_overrides)
             missing -= set(these_overrides.keys())
         return overrides
@@ -483,16 +483,16 @@ class FallbackOverridePolicy(BaseOverridePolicy):
             if not missing:
                 break
             these_overrides = policy.calculateBinaryOverrides(
-                dict((key, binaries[key]) for key in missing))
+                {key: binaries[key] for key in missing})
             overrides.update(these_overrides)
             missing -= set(these_overrides.keys())
         return overrides
 
 
 def calculate_target_das(distroseries, binaries):
-    arch_map = dict(
-        (arch.architecturetag, arch)
-        for arch in distroseries.enabled_architectures)
+    arch_map = {
+        arch.architecturetag: arch
+        for arch in distroseries.enabled_architectures}
 
     with_das = []
     for bpn, archtag in binaries:
diff --git a/lib/lp/soyuz/adapters/tests/test_overrides.py b/lib/lp/soyuz/adapters/tests/test_overrides.py
index f3f0d59..772e767 100644
--- a/lib/lp/soyuz/adapters/tests/test_overrides.py
+++ b/lib/lp/soyuz/adapters/tests/test_overrides.py
@@ -156,7 +156,7 @@ class TestFromExistingOverridePolicy(TestCaseWithFactory):
             spph.distroseries.main_archive, spph.distroseries, spph.pocket)
         with StormStatementRecorder() as recorder:
             policy.calculateSourceOverrides(
-                dict((spn, SourceOverride()) for spn in spns))
+                {spn: SourceOverride() for spn in spns})
         self.assertThat(recorder, HasQueryCount(Equals(3)))
 
     def test_no_binary_overrides(self):
@@ -366,7 +366,7 @@ class TestFromExistingOverridePolicy(TestCaseWithFactory):
             distroseries.main_archive, distroseries, pocket)
         with StormStatementRecorder() as recorder:
             policy.calculateBinaryOverrides(
-                dict(((bpn, das), BinaryOverride()) for bpn, das in bpns))
+                {(bpn, das): BinaryOverride() for bpn, das in bpns})
         self.assertThat(recorder, HasQueryCount(Equals(4)))
 
 
@@ -438,16 +438,16 @@ class TestUnknownOverridePolicy(TestCaseWithFactory):
             distroseries.main_archive, distroseries,
             PackagePublishingPocket.RELEASE)
         overrides = policy.calculateSourceOverrides(
-            dict(
-                (spn, SourceOverride(
-                    component=getUtility(IComponentSet)[component]))
+            {
+                spn: SourceOverride(
+                    component=getUtility(IComponentSet)[component])
                 for spn, component in
-                zip(spns, ('main', 'contrib', 'non-free'))))
-        expected = dict(
-            (spn, SourceOverride(
-                component=getUtility(IComponentSet)[component], new=True))
+                zip(spns, ('main', 'contrib', 'non-free'))})
+        expected = {
+            spn: SourceOverride(
+                component=getUtility(IComponentSet)[component], new=True)
             for spn, component in
-            zip(spns, ('universe', 'multiverse', 'multiverse')))
+            zip(spns, ('universe', 'multiverse', 'multiverse'))}
         self.assertEqual(expected, overrides)
 
     def test_unknown_binaries(self):
@@ -536,7 +536,7 @@ class TestFallbackOverridePolicy(TestCaseWithFactory):
             UnknownOverridePolicy(
                 distroseries.main_archive, distroseries, pocket)])
         overrides = policy.calculateSourceOverrides(
-            dict((spn, SourceOverride()) for spn in spns))
+            {spn: SourceOverride() for spn in spns})
         self.assertEqual(10, len(overrides))
         self.assertEqual(expected, overrides)
 
@@ -579,7 +579,7 @@ class TestFallbackOverridePolicy(TestCaseWithFactory):
             UnknownOverridePolicy(
                 distroseries.main_archive, distroseries, pocket)])
         overrides = policy.calculateBinaryOverrides(
-            dict(((bpn, das), BinaryOverride()) for bpn, das in bpns))
+            {(bpn, das): BinaryOverride() for bpn, das in bpns})
         self.assertEqual(5, len(overrides))
         self.assertEqual(expected, overrides)
 
@@ -620,6 +620,6 @@ class TestFallbackOverridePolicy(TestCaseWithFactory):
                 distroseries.main_archive, distroseries, pocket,
                 phased_update_percentage=50)])
         overrides = policy.calculateBinaryOverrides(
-            dict(((bpn, das), BinaryOverride()) for bpn, das in bpns))
+            {(bpn, das): BinaryOverride() for bpn, das in bpns})
         self.assertEqual(2, len(overrides))
         self.assertEqual(expected, overrides)
diff --git a/lib/lp/soyuz/browser/distributionsourcepackagerelease.py b/lib/lp/soyuz/browser/distributionsourcepackagerelease.py
index 1cc2bfe..f2fa74a 100644
--- a/lib/lp/soyuz/browser/distributionsourcepackagerelease.py
+++ b/lib/lp/soyuz/browser/distributionsourcepackagerelease.py
@@ -140,7 +140,7 @@ class DistributionSourcePackageReleaseView(LaunchpadView):
         def distroseries_sort_key(item):
             return Version(item.version)
         sorted_distroseries = sorted(
-            set(build.distro_series for build in cached_builds),
+            {build.distro_series for build in cached_builds},
             key=distroseries_sort_key, reverse=True)
 
         # Group builds as dictionaries.
diff --git a/lib/lp/soyuz/browser/queue.py b/lib/lp/soyuz/browser/queue.py
index 9ee371e..3888c6d 100644
--- a/lib/lp/soyuz/browser/queue.py
+++ b/lib/lp/soyuz/browser/queue.py
@@ -185,7 +185,7 @@ class QueueItemsView(LaunchpadView):
         """
         sprs = [spr for spr in source_package_releases if spr is not None]
         return getUtility(IPackagesetSet).getForPackages(
-            self.context, set(spr.sourcepackagenameID for spr in sprs))
+            self.context, {spr.sourcepackagenameID for spr in sprs})
 
     def loadPackageCopyJobs(self, uploads):
         """Batch-load `PackageCopyJob`s and related information."""
@@ -218,8 +218,8 @@ class QueueItemsView(LaunchpadView):
         # Both "u.sources" and "u.builds" below are preloaded by
         # self.context.getPackageUploads (which uses PackageUploadSet.getAll)
         # when building self.batchnav.
-        puses = sum([removeSecurityProxy(u.sources) for u in uploads], [])
-        pubs = sum([removeSecurityProxy(u.builds) for u in uploads], [])
+        puses = sum((removeSecurityProxy(u.sources) for u in uploads), [])
+        pubs = sum((removeSecurityProxy(u.builds) for u in uploads), [])
 
         source_sprs = load_related(
             SourcePackageRelease, puses, ['sourcepackagereleaseID'])
@@ -336,8 +336,8 @@ class QueueItemsView(LaunchpadView):
         permission_set = getUtility(IArchivePermissionSet)
         component_permissions = permission_set.componentsForQueueAdmin(
             self.context.main_archive, self.user)
-        allowed_components = set(
-            permission.component for permission in component_permissions)
+        allowed_components = {
+            permission.component for permission in component_permissions}
         pocket_permissions = permission_set.pocketsForQueueAdmin(
             self.context.main_archive, self.user)
 
diff --git a/lib/lp/soyuz/model/archive.py b/lib/lp/soyuz/model/archive.py
index 6da89d1..458481a 100644
--- a/lib/lp/soyuz/model/archive.py
+++ b/lib/lp/soyuz/model/archive.py
@@ -1287,7 +1287,7 @@ class Archive(SQLBase):
             count_map['total'].append(BuildStatus.NEEDSBUILD)
 
         # Initialize all the counts in the map to zero:
-        build_counts = dict((count_type, 0) for count_type in count_map)
+        build_counts = {count_type: 0 for count_type in count_map}
 
         # For each count type that we want to return ('failed', 'total'),
         # there may be a number of corresponding buildstate counts.
@@ -1497,8 +1497,8 @@ class Archive(SQLBase):
             components = [components]
         component_permissions = self.getComponentsForQueueAdmin(user)
         if not component_permissions.is_empty():
-            allowed_components = set(
-                permission.component for permission in component_permissions)
+            allowed_components = {
+                permission.component for permission in component_permissions}
             # The intersection of allowed_components and components must be
             # equal to components to allow the operation to go ahead.
             if allowed_components.intersection(components) == set(components):
@@ -2062,7 +2062,7 @@ class Archive(SQLBase):
         # Check for duplicate names.
         token_set = getUtility(IArchiveAuthTokenSet)
         dup_tokens = token_set.getActiveNamedTokensForArchive(self, names)
-        dup_names = set(token.name for token in dup_tokens)
+        dup_names = {token.name for token in dup_tokens}
 
         values = [
             (name, create_token(20), self) for name in set(names) - dup_names]
diff --git a/lib/lp/soyuz/model/archivefile.py b/lib/lp/soyuz/model/archivefile.py
index 680c6b4..e6b126d 100644
--- a/lib/lp/soyuz/model/archivefile.py
+++ b/lib/lp/soyuz/model/archivefile.py
@@ -131,7 +131,7 @@ class ArchiveFileSet:
         """See `IArchiveFileSet`."""
         clauses = [
             ArchiveFile.id.is_in(
-                set(archive_file.id for archive_file in archive_files)),
+                {archive_file.id for archive_file in archive_files}),
             ArchiveFile.library_file == LibraryFileAlias.id,
             LibraryFileAlias.content == LibraryFileContent.id,
             ]
@@ -151,7 +151,7 @@ class ArchiveFileSet:
         """See `IArchiveFileSet`."""
         clauses = [
             ArchiveFile.id.is_in(
-                set(archive_file.id for archive_file in archive_files)),
+                {archive_file.id for archive_file in archive_files}),
             ArchiveFile.library_file == LibraryFileAlias.id,
             LibraryFileAlias.content == LibraryFileContent.id,
             ]
diff --git a/lib/lp/soyuz/model/binarypackagebuild.py b/lib/lp/soyuz/model/binarypackagebuild.py
index 330a1e3..511c975 100644
--- a/lib/lp/soyuz/model/binarypackagebuild.py
+++ b/lib/lp/soyuz/model/binarypackagebuild.py
@@ -1340,8 +1340,8 @@ class BinaryPackageBuildSet(SpecificBuildFarmJobSourceMixin):
             if build is not None:
                 relevant_builds.append(build)
 
-        skip_archtags = set(
-            bpb.distro_arch_series.architecturetag for bpb in relevant_builds)
+        skip_archtags = {
+            bpb.distro_arch_series.architecturetag for bpb in relevant_builds}
         # We need to assign the arch-indep role to a build unless an
         # arch-indep build has already succeeded, or another build in
         # this series already has it set.
@@ -1356,13 +1356,13 @@ class BinaryPackageBuildSet(SpecificBuildFarmJobSourceMixin):
         # Processor 1 is i386, a good arch-indep candidate, is a
         # total coincidence and this isn't a hack. I promise.
         need_archs = sorted(
-            [das for das in
+            (das for das in
              self._getAllowedArchitectures(
                  archive,
                  architectures_available
                     or distroseries.buildable_architectures)
              if das.architecturetag not in skip_archtags and
-                das.isSourceIncluded(sourcepackagerelease.sourcepackagename)],
+                das.isSourceIncluded(sourcepackagerelease.sourcepackagename)),
             key=attrgetter('processor.id'))
         nominated_arch_indep_tag = (
             distroseries.nominatedarchindep.architecturetag
diff --git a/lib/lp/soyuz/model/distroseriesdifferencejob.py b/lib/lp/soyuz/model/distroseriesdifferencejob.py
index 57582bf..b631bae 100644
--- a/lib/lp/soyuz/model/distroseriesdifferencejob.py
+++ b/lib/lp/soyuz/model/distroseriesdifferencejob.py
@@ -220,11 +220,11 @@ class DistroSeriesDifferenceJob(DistributionJobDerived):
             Job._status.is_in(Job.PENDING_STATUSES),
             DistributionJob.distroseries == derived_series)
 
-        parent_series_ids = set(
-            dsd.parent_series.id for dsd in distroseriesdifferences)
-        keyed_dsds = dict(
-            (dsd.source_package_name.id, dsd)
-            for dsd in distroseriesdifferences)
+        parent_series_ids = {
+            dsd.parent_series.id for dsd in distroseriesdifferences}
+        keyed_dsds = {
+            dsd.source_package_name.id: dsd
+            for dsd in distroseriesdifferences}
         jobs_by_dsd = {}
         for job in jobs:
             if job.metadata["parent_series"] not in parent_series_ids:
diff --git a/lib/lp/soyuz/model/publishing.py b/lib/lp/soyuz/model/publishing.py
index ff4d2bb..5053815 100644
--- a/lib/lp/soyuz/model/publishing.py
+++ b/lib/lp/soyuz/model/publishing.py
@@ -320,8 +320,8 @@ class SourcePackagePublishingHistory(SQLBase, ArchivePublisherBase):
                 Desc(BinaryPackagePublishingHistory.id)))
 
         # Preload attached BinaryPackageReleases.
-        bpr_ids = set(
-            pub.binarypackagereleaseID for pub in binary_publications)
+        bpr_ids = {
+            pub.binarypackagereleaseID for pub in binary_publications}
         list(Store.of(self).find(
             BinaryPackageRelease, BinaryPackageRelease.id.is_in(bpr_ids)))
 
@@ -337,7 +337,7 @@ class SourcePackagePublishingHistory(SQLBase, ArchivePublisherBase):
                 get_property_cache(bpr).files = bpfs_by_bpr[bpr]
 
             # Preload LibraryFileAliases.
-            lfa_ids = set(bpf.libraryfileID for bpf in bpfs)
+            lfa_ids = {bpf.libraryfileID for bpf in bpfs}
             list(Store.of(self).find(
                 LibraryFileAlias, LibraryFileAlias.id.is_in(lfa_ids)))
 
@@ -1028,7 +1028,7 @@ def expand_binary_requests(distroseries, binaries):
     """
 
     archs = list(distroseries.enabled_architectures)
-    arch_map = dict((arch.architecturetag, arch) for arch in archs)
+    arch_map = {arch.architecturetag: arch for arch in archs}
 
     expanded = []
     for bpr, overrides in six.iteritems(binaries):
@@ -1155,10 +1155,10 @@ class PublishingSet:
                     bpph.distroarchseries.architecturetag)] = bpph
             with_overrides = {}
             overrides = policy.calculateBinaryOverrides(
-                dict(
-                    ((bpn, archtag), BinaryOverride(
-                        source_override=source_override))
-                    for bpn, archtag in bpn_archtag.keys()))
+                {
+                    (bpn, archtag): BinaryOverride(
+                        source_override=source_override)
+                    for bpn, archtag in bpn_archtag.keys()})
             for (bpn, archtag), override in overrides.items():
                 bpph = bpn_archtag[(bpn, archtag)]
                 new_component = override.component or bpph.component
@@ -1183,9 +1183,9 @@ class PublishingSet:
                     ddebs.remove(maybe_ddeb)
                     with_overrides[maybe_ddeb] = calculated
         else:
-            with_overrides = dict(
-                (bpph.binarypackagerelease, (bpph.component, bpph.section,
-                 bpph.priority, None)) for bpph in bpphs)
+            with_overrides = {
+                bpph.binarypackagerelease: (bpph.component, bpph.section,
+                 bpph.priority, None) for bpph in bpphs}
         if not with_overrides:
             return list()
         copied_from_archives = {
@@ -1729,8 +1729,8 @@ class PublishingSet:
             return
         assert len(sources) + len(binaries) == len(pubs)
 
-        locations = set(
-            (pub.archive, pub.distroseries, pub.pocket) for pub in pubs)
+        locations = {
+            (pub.archive, pub.distroseries, pub.pocket) for pub in pubs}
         for archive, distroseries, pocket in locations:
             if not archive.canModifySuite(distroseries, pocket):
                 raise DeletionError(
diff --git a/lib/lp/soyuz/model/queue.py b/lib/lp/soyuz/model/queue.py
index c5ff4f0..c538f85 100644
--- a/lib/lp/soyuz/model/queue.py
+++ b/lib/lp/soyuz/model/queue.py
@@ -1060,8 +1060,8 @@ class PackageUpload(SQLBase):
             permission_set = getUtility(IArchivePermissionSet)
             permissions = permission_set.componentsForQueueAdmin(
                 self.distroseries.main_archive, user)
-            allowed_components = set(
-                permission.component for permission in permissions)
+            allowed_components = {
+                permission.component for permission in permissions}
         assert allowed_components is not None, (
             "Must provide allowed_components for non-webservice calls.")
 
@@ -1116,8 +1116,8 @@ class PackageUpload(SQLBase):
             permission_set = getUtility(IArchivePermissionSet)
             permissions = permission_set.componentsForQueueAdmin(
                 self.distroseries.main_archive, user)
-            allowed_components = set(
-                permission.component for permission in permissions)
+            allowed_components = {
+                permission.component for permission in permissions}
         assert allowed_components is not None, (
             "Must provide allowed_components for non-webservice calls.")
 
diff --git a/lib/lp/soyuz/model/sourcepackagerelease.py b/lib/lp/soyuz/model/sourcepackagerelease.py
index 2615be9..93eb514 100644
--- a/lib/lp/soyuz/model/sourcepackagerelease.py
+++ b/lib/lp/soyuz/model/sourcepackagerelease.py
@@ -249,8 +249,8 @@ class SourcePackageRelease(SQLBase):
 
     @cachedproperty
     def published_archives(self):
-        archives = set(
-            pub.archive for pub in self.publishings.prejoin(['archive']))
+        archives = {
+            pub.archive for pub in self.publishings.prejoin(['archive'])}
         return sorted(archives, key=operator.attrgetter('id'))
 
     def addFile(self, file, filetype=None):
diff --git a/lib/lp/soyuz/scripts/custom_uploads_copier.py b/lib/lp/soyuz/scripts/custom_uploads_copier.py
index c6445fe..55cd1c7 100644
--- a/lib/lp/soyuz/scripts/custom_uploads_copier.py
+++ b/lib/lp/soyuz/scripts/custom_uploads_copier.py
@@ -79,7 +79,7 @@ class CustomUploadsCopier:
         uploads = source_series.getPackageUploads(
             pocket=source_pocket, custom_type=list(self.copyable_types))
         load_referencing(PackageUploadCustom, uploads, ['packageuploadID'])
-        customs = sum([list(upload.customfiles) for upload in uploads], [])
+        customs = sum((list(upload.customfiles) for upload in uploads), [])
         return sorted(
             filter(self.isCopyable, customs),
             key=attrgetter('id'), reverse=True)
diff --git a/lib/lp/soyuz/scripts/gina/handlers.py b/lib/lp/soyuz/scripts/gina/handlers.py
index e4b8eb6..b527ab7 100644
--- a/lib/lp/soyuz/scripts/gina/handlers.py
+++ b/lib/lp/soyuz/scripts/gina/handlers.py
@@ -503,9 +503,9 @@ class SourcePackageHandler:
         log.debug("Found a source package for %s (%s) in %s" % (sp_name,
             sp_version, sp_component))
         dsc_contents = parse_tagfile(dsc_path)
-        dsc_contents = dict([
-            (name.lower(), value) for
-            (name, value) in six.iteritems(dsc_contents)])
+        dsc_contents = {
+            name.lower(): value for
+            (name, value) in six.iteritems(dsc_contents)}
 
         # Since the dsc doesn't know, we add in the directory, package
         # component and section
diff --git a/lib/lp/soyuz/scripts/gina/packages.py b/lib/lp/soyuz/scripts/gina/packages.py
index 718f4fa..e8b6dae 100644
--- a/lib/lp/soyuz/scripts/gina/packages.py
+++ b/lib/lp/soyuz/scripts/gina/packages.py
@@ -328,7 +328,7 @@ class SourcePackageData(AbstractPackageData):
         'component',
         ]
 
-    _known_fields = set(k.lower() for k in DSCFile.known_fields)
+    _known_fields = {k.lower() for k in DSCFile.known_fields}
 
     def __init__(self, **args):
         for k, v in args.items():
@@ -454,7 +454,7 @@ class BinaryPackageData(AbstractPackageData):
         'priority',
         ]
 
-    _known_fields = set(k.lower() for k in BaseBinaryUploadFile.known_fields)
+    _known_fields = {k.lower() for k in BaseBinaryUploadFile.known_fields}
 
     # Set in __init__
     source = None
diff --git a/lib/lp/soyuz/scripts/initialize_distroseries.py b/lib/lp/soyuz/scripts/initialize_distroseries.py
index 9c9a2ae..1ca534d 100644
--- a/lib/lp/soyuz/scripts/initialize_distroseries.py
+++ b/lib/lp/soyuz/scripts/initialize_distroseries.py
@@ -430,10 +430,10 @@ class InitializeDistroSeries:
                 self.distroseries.getDistroArchSeries(self.archindep_archtag))
 
     def _potential_nominated_arches(self, parent_list):
-        parent_indep_archtags = set(
+        parent_indep_archtags = {
             parent.nominatedarchindep.architecturetag
             for parent in parent_list
-            if parent.nominatedarchindep is not None)
+            if parent.nominatedarchindep is not None}
 
         if len(self.arches) == 0:
             return parent_indep_archtags
diff --git a/lib/lp/soyuz/scripts/packagecopier.py b/lib/lp/soyuz/scripts/packagecopier.py
index 9f365b8..c1fb6cb 100644
--- a/lib/lp/soyuz/scripts/packagecopier.py
+++ b/lib/lp/soyuz/scripts/packagecopier.py
@@ -192,7 +192,7 @@ def check_copy_permissions(person, archive, series, pocket, sources,
 
     if move:
         roles = IPersonRoles(person)
-        for source_archive in set(source.archive for source in sources):
+        for source_archive in {source.archive for source in sources}:
             # XXX cjwatson 2019-10-09: Checking the archive rather than the
             # SPPH duplicates security adapter logic, which is unfortunate;
             # but too much of the logic required to use
@@ -367,9 +367,9 @@ class CopyChecker:
 
             # Update published binaries inventory for the conflicting
             # candidates.
-            archive_binaries = set(
+            archive_binaries = {
                 pub_binary.binarypackagerelease.id
-                for pub_binary in candidate.getBuiltBinaries())
+                for pub_binary in candidate.getBuiltBinaries()}
             published_binaries.update(archive_binaries)
 
         if not self.include_binaries:
@@ -383,9 +383,9 @@ class CopyChecker:
             # correct to assume that the set of BinaryPackageReleases being
             # copied can only be a superset of the set of
             # BinaryPackageReleases published in the destination archive.
-            copied_binaries = set(
+            copied_binaries = {
                 pub.binarypackagerelease.id
-                for pub in source.getBuiltBinaries())
+                for pub in source.getBuiltBinaries()}
             if not copied_binaries.issuperset(published_binaries):
                 raise CannotCopy(
                     "binaries conflicting with the existing ones")
@@ -751,9 +751,9 @@ def _do_direct_copy(source, archive, series, pocket, include_binaries,
 
         if binary_copies is not None:
             copies.extend(binary_copies)
-            binary_uploads = set(
+            binary_uploads = {
                 bpph.binarypackagerelease.build.package_upload
-                for bpph in binary_copies)
+                for bpph in binary_copies}
             for binary_upload in binary_uploads:
                 if binary_upload is not None:
                     custom_files.extend(binary_upload.customfiles)
diff --git a/lib/lp/soyuz/scripts/retrydepwait.py b/lib/lp/soyuz/scripts/retrydepwait.py
index 4617af7..a6a41af 100644
--- a/lib/lp/soyuz/scripts/retrydepwait.py
+++ b/lib/lp/soyuz/scripts/retrydepwait.py
@@ -58,7 +58,7 @@ class RetryDepwaitTunableLoop(TunableLoop):
             PocketChroot.distroarchseriesID.is_in(
                 b.distro_arch_series_id for b in bpbs),
             PocketChroot.chroot != None)
-        chroot_series = set(chroot.distroarchseriesID for chroot in chroots)
+        chroot_series = {chroot.distroarchseriesID for chroot in chroots}
         for build in bpbs:
             if (build.distro_arch_series.distroseries.status ==
                     SeriesStatus.OBSOLETE
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 c390d21..8a0de44 100644
--- a/lib/lp/soyuz/scripts/tests/test_custom_uploads_copier.py
+++ b/lib/lp/soyuz/scripts/tests/test_custom_uploads_copier.py
@@ -21,9 +21,9 @@ from lp.testing.layers import (
 def list_custom_uploads(distroseries):
     """Return a list of all `PackageUploadCustom`s for `distroseries`."""
     return sum(
-        [
+        (
             list(upload.customfiles)
-            for upload in distroseries.getPackageUploads()],
+            for upload in distroseries.getPackageUploads()),
         [])
 
 
diff --git a/lib/lp/soyuz/scripts/tests/test_initialize_distroseries.py b/lib/lp/soyuz/scripts/tests/test_initialize_distroseries.py
index e06e5a5..4079947 100644
--- a/lib/lp/soyuz/scripts/tests/test_initialize_distroseries.py
+++ b/lib/lp/soyuz/scripts/tests/test_initialize_distroseries.py
@@ -653,7 +653,7 @@ class TestInitializeDistroSeries(InitializationHelperTestCase):
         self.assertEqual(
             parent_udev_pubs.count(), child_udev_pubs.count())
         self.assertEqual(
-            {child_pocket}, set(pub.pocket for pub in child_udev_pubs))
+            {child_pocket}, {pub.pocket for pub in child_udev_pubs})
         parent_arch_udev_pubs = parent.main_archive.getAllPublishedBinaries(
             distroarchseries=parent[parent_das.architecturetag], name=u'udev')
         child_arch_udev_pubs = child.main_archive.getAllPublishedBinaries(
@@ -661,7 +661,7 @@ class TestInitializeDistroSeries(InitializationHelperTestCase):
         self.assertEqual(
             parent_arch_udev_pubs.count(), child_arch_udev_pubs.count())
         self.assertEqual(
-            {child_pocket}, set(pub.pocket for pub in child_arch_udev_pubs))
+            {child_pocket}, {pub.pocket for pub in child_arch_udev_pubs})
         # And the binary package, and linked source package look fine too.
         udev_bin = child_arch_udev_pubs[0].binarypackagerelease
         self.assertEqual(udev_bin.title, u'udev-0.1-1')
@@ -776,9 +776,9 @@ class TestInitializeDistroSeries(InitializationHelperTestCase):
         published_sources = child.main_archive.getPublishedSources(
             distroseries=child)
         pub_sources = sorted(
-            [(s.sourcepackagerelease.sourcepackagename.name,
+            (s.sourcepackagerelease.sourcepackagename.name,
               s.sourcepackagerelease.version)
-                for s in published_sources])
+                for s in published_sources)
         self.assertContentEqual(
             [(u'udev', u'0.1-1'), (u'firefox', u'2.1')],
             pub_sources)
@@ -1465,9 +1465,9 @@ class TestInitializeDistroSeries(InitializationHelperTestCase):
             distroseries=child)
         self.assertEqual(2, published_sources.count())
         pub_sources = sorted(
-            [(s.sourcepackagerelease.sourcepackagename.name,
+            (s.sourcepackagerelease.sourcepackagename.name,
               s.sourcepackagerelease.version)
-                for s in published_sources])
+                for s in published_sources)
         self.assertEqual(
             [(u'p1', u'1.2'), (u'p2', u'1.5')],
             pub_sources)
diff --git a/lib/lp/soyuz/scripts/tests/test_populatearchive.py b/lib/lp/soyuz/scripts/tests/test_populatearchive.py
index 228deb7..c3b810f 100644
--- a/lib/lp/soyuz/scripts/tests/test_populatearchive.py
+++ b/lib/lp/soyuz/scripts/tests/test_populatearchive.py
@@ -390,12 +390,12 @@ class TestPopulateArchiveScript(TestCaseWithFactory):
         self._verifyClonedSourcePackages(
             second_stage, hoary,
             # The set of packages that were superseded in the target archive.
-            obsolete=set(['alsa-utils 1.0.9a-4ubuntu1 in hoary']),
+            obsolete={'alsa-utils 1.0.9a-4ubuntu1 in hoary'},
             # The set of packages that are new/fresher in the source archive.
-            new=set([
+            new={
                 'alsa-utils 2.0 in hoary',
                 'new-in-second-round 1.0 in hoary',
-                ]))
+                })
 
         # Now populate a 3rd copy archive from the first ubuntu/hoary
         # snapshot.
@@ -421,12 +421,12 @@ class TestPopulateArchiveScript(TestCaseWithFactory):
         self._verifyClonedSourcePackages(
             copy_archive, hoary,
             # The set of packages that were superseded in the target archive.
-            obsolete=set(['alsa-utils 1.0.9a-4ubuntu1 in hoary']),
+            obsolete={'alsa-utils 1.0.9a-4ubuntu1 in hoary'},
             # The set of packages that are new/fresher in the source archive.
-            new=set([
+            new={
                 'alsa-utils 2.0 in hoary',
                 'new-in-second-round 1.0 in hoary',
-                ]))
+                })
 
     def testUnknownOriginArchive(self):
         """Try copy archive population with a unknown origin archive.
@@ -656,7 +656,7 @@ class TestPopulateArchiveScript(TestCaseWithFactory):
     def _getPendingPackageNames(self, archive, series):
         sources = archive.getPublishedSources(
             distroseries=series, status=self.pending_statuses)
-        return set(source.displayname for source in sources)
+        return {source.displayname for source in sources}
 
     def _prepareMergeCopy(self):
         """Add a fresher and a new package to ubuntu/hoary.
diff --git a/lib/lp/soyuz/scripts/tests/test_ppa_apache_log_parser.py b/lib/lp/soyuz/scripts/tests/test_ppa_apache_log_parser.py
index 187323c..50db145 100644
--- a/lib/lp/soyuz/scripts/tests/test_ppa_apache_log_parser.py
+++ b/lib/lp/soyuz/scripts/tests/test_ppa_apache_log_parser.py
@@ -150,8 +150,8 @@ class TestScriptRunning(TestCaseWithFactory):
               austria,
               1)],
             sorted(
-                [(result.binary_package_release, result.archive, result.day,
-                  result.country, result.count) for result in results],
+                ((result.binary_package_release, result.archive, result.day,
+                  result.country, result.count) for result in results),
                  key=lambda r: (
                      r[0].id, r[2],
                      r[3] is not None, r[3].name if r[3] else None)))
diff --git a/lib/lp/soyuz/tests/test_archive.py b/lib/lp/soyuz/tests/test_archive.py
index 1207443..ac1fb04 100644
--- a/lib/lp/soyuz/tests/test_archive.py
+++ b/lib/lp/soyuz/tests/test_archive.py
@@ -1364,7 +1364,7 @@ class TestArchiveTokens(TestCaseWithFactory):
         # Preload feature flag so it is cached.
         getFeatureFlag(NAMED_AUTH_TOKEN_FEATURE_FLAG)
         with StormStatementRecorder() as recorder1:
-            self.private_ppa.newNamedAuthTokens(("tok1"))
+            self.private_ppa.newNamedAuthTokens("tok1")
         with StormStatementRecorder() as recorder2:
             self.private_ppa.newNamedAuthTokens(("tok1", "tok2", "tok3"))
         self.assertThat(recorder2, HasQueryCount.byEquality(recorder1))
@@ -2162,7 +2162,7 @@ class TestComponents(TestCaseWithFactory):
         # restriction isn't relevant to this test.
         ap_set = removeSecurityProxy(getUtility(IArchivePermissionSet))
         ap = ap_set.newComponentUploader(archive, person, component)
-        self.assertEqual(set([ap]),
+        self.assertEqual({ap},
             set(archive.getComponentsForUploader(person)))
 
 
@@ -2187,7 +2187,7 @@ class TestPockets(TestCaseWithFactory):
         ap_set = removeSecurityProxy(getUtility(IArchivePermissionSet))
         ap = ap_set.newPocketUploader(
             archive, person, PackagePublishingPocket.SECURITY)
-        self.assertEqual(set([ap]), set(archive.getPocketsForUploader(person)))
+        self.assertEqual({ap}, set(archive.getPocketsForUploader(person)))
 
 
 class TestValidatePPA(TestCaseWithFactory):
@@ -2339,7 +2339,7 @@ class TestGetComponentsForSeries(TestCaseWithFactory):
         clear_property_cache(self.series)
 
         self.assertEqual(
-            set((self.comp1, self.comp2)),
+            {self.comp1, self.comp2},
             set(archive.getComponentsForSeries(self.series)))
 
     def test_partner_component_for_partner_archive(self):
@@ -2809,7 +2809,7 @@ class TestGetPublishedSourcesWebService(TestCaseWithFactory):
         # via a wrapper to improving performance (by reducing the
         # number of queries issued)
         ppa = self.createTestingPPA()
-        ppa_url = '/~{0}/+archive/ubuntu/ppa'.format(ppa.owner.name)
+        ppa_url = '/~{}/+archive/ubuntu/ppa'.format(ppa.owner.name)
         webservice = webservice_for_person(
             ppa.owner, permission=OAuthPermission.READ_PRIVATE)
 
diff --git a/lib/lp/soyuz/tests/test_distroseriesdifferencejob.py b/lib/lp/soyuz/tests/test_distroseriesdifferencejob.py
index fcba15b..e9f007d 100644
--- a/lib/lp/soyuz/tests/test_distroseriesdifferencejob.py
+++ b/lib/lp/soyuz/tests/test_distroseriesdifferencejob.py
@@ -388,12 +388,12 @@ class TestDistroSeriesDifferenceJobSource(TestCaseWithFactory):
                 sourcepackagerelease=self.factory.makeSourcePackageRelease(
                     sourcepackagename=spn))
 
-        job_counts = dict(
-            (dsp.derived_series, len(find_waiting_jobs(
-                dsp.derived_series, spn, dsp.parent_series)))
-            for dsp in dsps)
+        job_counts = {
+            dsp.derived_series: len(find_waiting_jobs(
+                dsp.derived_series, spn, dsp.parent_series))
+            for dsp in dsps}
         self.assertEqual(
-            dict((distroseries, 1) for distroseries in series),
+            {distroseries: 1 for distroseries in series},
             job_counts)
 
     def test_createForSPPHs_behaves_sensibly_if_job_already_exists(self):
@@ -900,9 +900,9 @@ class TestDistroSeriesDifferenceJobPermissions(TestCaseWithFactory):
         dsp = self.factory.makeDistroSeriesParent()
         parent = dsp.parent_series
         derived = dsp.derived_series
-        packages = dict(
-            (user, self.factory.makeSourcePackageName())
-            for user in script_users)
+        packages = {
+            user: self.factory.makeSourcePackageName()
+            for user in script_users}
         for user in script_users:
             switch_dbuser(user)
             try:
diff --git a/lib/lp/soyuz/tests/test_packagecloner.py b/lib/lp/soyuz/tests/test_packagecloner.py
index 900a24f..a527f9a 100644
--- a/lib/lp/soyuz/tests/test_packagecloner.py
+++ b/lib/lp/soyuz/tests/test_packagecloner.py
@@ -44,7 +44,7 @@ class PackageClonerTests(TestCaseWithFactory):
         that distroseries are checked against a set of PackageInfo to
         ensure that the correct package names and versions are published.
         """
-        expected_set = set([(info.name, info.version) for info in expected])
+        expected_set = {(info.name, info.version) for info in expected}
         sources = archive.getPublishedSources(
             distroseries=distroseries,
             status=active_publishing_status)
@@ -129,7 +129,7 @@ class PackageClonerTests(TestCaseWithFactory):
         created for it.
         """
         expected_builds = list(
-            [(info.name, info.version) for info in package_infos])
+            (info.name, info.version) for info in package_infos)
         builds = list(
             getUtility(IBinaryPackageBuildSet).getBuildsForArchive(
             archive, status=BuildStatus.NEEDSBUILD))
diff --git a/lib/lp/soyuz/tests/test_packagecopyjob.py b/lib/lp/soyuz/tests/test_packagecopyjob.py
index 998992f..50a65c8 100644
--- a/lib/lp/soyuz/tests/test_packagecopyjob.py
+++ b/lib/lp/soyuz/tests/test_packagecopyjob.py
@@ -273,7 +273,7 @@ class PlainPackageCopyJobTests(TestCaseWithFactory, LocalTestHelper):
         job_ids = list(job_source.createMultiple(copy_tasks, requester))
         jobs = list(job_source.getActiveJobs(derived_series.main_archive))
         self.assertContentEqual(job_ids, [job.id for job in jobs])
-        self.assertEqual(len(copy_tasks), len(set([job.job for job in jobs])))
+        self.assertEqual(len(copy_tasks), len({job.job for job in jobs}))
         # Get jobs into the same order as copy_tasks, for ease of
         # comparison.
         if jobs[0].package_name != mother_package.name:
@@ -291,7 +291,7 @@ class PlainPackageCopyJobTests(TestCaseWithFactory, LocalTestHelper):
         self.assertEqual(copy_tasks, requested_copies)
 
         # The passed requester should be the same on all jobs.
-        actual_requester = set(job.requester for job in jobs)
+        actual_requester = {job.requester for job in jobs}
         self.assertEqual(1, len(actual_requester))
         self.assertEqual(requester, jobs[0].requester)
 
diff --git a/lib/lp/soyuz/tests/test_packageupload.py b/lib/lp/soyuz/tests/test_packageupload.py
index 12d8c1f..24fb049 100644
--- a/lib/lp/soyuz/tests/test_packageupload.py
+++ b/lib/lp/soyuz/tests/test_packageupload.py
@@ -1292,9 +1292,9 @@ class TestPackageUploadWebservice(TestCaseWithFactory):
 
         self.assertEqual("New", ws_upload.status)
         self.assertEqual(
-            set(["universe"]),
-            set(binary["component"]
-                for binary in ws_upload.getBinaryProperties()))
+            {"universe"},
+            {binary["component"]
+                for binary in ws_upload.getBinaryProperties()})
         self.assertRaises(
             Unauthorized, ws_upload.overrideBinaries,
             changes=[{"component": "main"}])
@@ -1306,9 +1306,9 @@ class TestPackageUploadWebservice(TestCaseWithFactory):
         transaction.commit()
 
         self.assertEqual(
-            set(["main"]),
-            set(binary["component"]
-                for binary in ws_upload.getBinaryProperties()))
+            {"main"},
+            {binary["component"]
+                for binary in ws_upload.getBinaryProperties()})
         self.assertRaises(
             Unauthorized, ws_upload.overrideBinaries,
             changes=[{"component": "universe"}])
diff --git a/lib/lp/soyuz/tests/test_publishing.py b/lib/lp/soyuz/tests/test_publishing.py
index d3d085e..ec6f426 100644
--- a/lib/lp/soyuz/tests/test_publishing.py
+++ b/lib/lp/soyuz/tests/test_publishing.py
@@ -1381,7 +1381,7 @@ class TestGetActiveArchSpecificPublications(TestCaseWithFactory):
         bpphs = self.makeBPPHs(spr, len(PackagePublishingStatus.items))
         for bpph, status in zip(bpphs, PackagePublishingStatus.items):
             bpph.status = status
-        by_status = dict((bpph.status, bpph) for bpph in bpphs)
+        by_status = {bpph.status: bpph for bpph in bpphs}
         self.assertContentEqual(
             [by_status[status] for status in active_publishing_status],
             getUtility(IPublishingSet).getActiveArchSpecificPublications(
@@ -1402,10 +1402,10 @@ class TestPublishBinaries(TestCaseWithFactory):
             'archive': archive,
             'distroseries': distroseries,
             'pocket': PackagePublishingPocket.BACKPORTS,
-            'binaries': dict(
-                (bpr, (self.factory.makeComponent(),
+            'binaries': {
+                bpr: (self.factory.makeComponent(),
                  self.factory.makeSection(),
-                 PackagePublishingPriority.REQUIRED, 50)) for bpr in bprs),
+                 PackagePublishingPriority.REQUIRED, 50) for bpr in bprs},
             }
 
     def test_architecture_dependent(self):
diff --git a/lib/lp/testing/__init__.py b/lib/lp/testing/__init__.py
index db384ae..24c4eea 100644
--- a/lib/lp/testing/__init__.py
+++ b/lib/lp/testing/__init__.py
@@ -784,9 +784,9 @@ class TestCase(testtools.TestCase, fixtures.TestWithFixtures):
             expected, set(used_permissions.values()),
             'Unexpected %s permissions' % type_)
         for permission in expected_permissions:
-            attribute_names = set(
+            attribute_names = {
                 name for name, value in used_permissions.items()
-                if value == permission)
+                if value == permission}
             self.assertEqual(
                 expected_permissions[permission], attribute_names,
                 'Unexpected set of attributes with %s permission %s:\n'
diff --git a/lib/lp/testing/mail_helpers.py b/lib/lp/testing/mail_helpers.py
index 0cb0a0c..5792861 100644
--- a/lib/lp/testing/mail_helpers.py
+++ b/lib/lp/testing/mail_helpers.py
@@ -53,7 +53,7 @@ def pop_notifications(sort_key=None, commit=True):
 
 def sort_addresses(header):
     """Sort an address-list in an email header field body."""
-    addresses = set(address.strip() for address in header.split(','))
+    addresses = {address.strip() for address in header.split(',')}
     return ", ".join(sorted(addresses))
 
 
@@ -86,9 +86,9 @@ def print_emails(include_reply_to=False, group_similar=False,
     if notifications is None:
         notifications = pop_notifications()
     for message in notifications:
-        recipients = set(
+        recipients = {
             recipient.strip()
-            for recipient in message['To'].split(','))
+            for recipient in message['To'].split(',')}
         body = message.get_payload(decode=decode)
         if group_similar:
             # Strip the first line as it's different for each recipient.
diff --git a/lib/lp/testing/pages.py b/lib/lp/testing/pages.py
index 15cb641..5c7a2fa 100644
--- a/lib/lp/testing/pages.py
+++ b/lib/lp/testing/pages.py
@@ -911,10 +911,10 @@ def PageTestSuite(storydir, package=None, setUp=setUpGlobs, **kw):
     package = doctest._normalize_module(package)
     abs_storydir = doctest._module_relative_path(package, storydir)
 
-    filenames = set(
+    filenames = {
         filename
         for filename in os.listdir(abs_storydir)
-        if filename.lower().endswith('.txt'))
+        if filename.lower().endswith('.txt')}
 
     suite = unittest.TestSuite()
     # Add tests to the suite individually.
diff --git a/lib/lp/testing/swift/fakeswift.py b/lib/lp/testing/swift/fakeswift.py
index 38f4f6d..e3dd5e7 100644
--- a/lib/lp/testing/swift/fakeswift.py
+++ b/lib/lp/testing/swift/fakeswift.py
@@ -125,8 +125,8 @@ class FakeKeystone(resource.Resource):
         if "auth" not in credentials:
             request.setResponseCode(http.FORBIDDEN)
             return b""
-        if (("tenantName" not in credentials["auth"] or
-            "passwordCredentials" not in credentials["auth"])):
+        if ("tenantName" not in credentials["auth"] or
+            "passwordCredentials" not in credentials["auth"]):
             request.setResponseCode(http.FORBIDDEN)
             return b""
         tenant_name = credentials["auth"]["tenantName"]
@@ -502,8 +502,8 @@ class FakeSwift(resource.Resource):
         container = self.containers.get(name, None)
 
         # if we operate on a key, pass control
-        if (((request.postpath and request.postpath[0]) or
-             (not request.postpath and request.method == b"GET"))):
+        if ((request.postpath and request.postpath[0]) or
+             (not request.postpath and request.method == b"GET")):
             if container is None:
                 # container does not exist, yet we attempt operation on
                 # an object from that container
diff --git a/lib/lp/testing/swift/tests/test_fixture.py b/lib/lp/testing/swift/tests/test_fixture.py
index 235a4cc..431a6dd 100644
--- a/lib/lp/testing/swift/tests/test_fixture.py
+++ b/lib/lp/testing/swift/tests/test_fixture.py
@@ -207,7 +207,7 @@ class TestSwiftFixture(TestCase):
 
     def test_env(self):
         self.assertThat(config.librarian_server, MatchesStructure.byEquality(
-            os_auth_url='http://localhost:{0}/keystone/v2.0/'.format(
+            os_auth_url='http://localhost:{}/keystone/v2.0/'.format(
                 self.swift_fixture.daemon_port),
             os_username=fakeswift.DEFAULT_USERNAME,
             os_password=fakeswift.DEFAULT_PASSWORD,
@@ -217,12 +217,12 @@ class TestSwiftFixture(TestCase):
     def test_old_instance_env(self):
         old_swift_fixture = self.useFixture(SwiftFixture(old_instance=True))
         self.assertThat(config.librarian_server, MatchesStructure.byEquality(
-            os_auth_url='http://localhost:{0}/keystone/v2.0/'.format(
+            os_auth_url='http://localhost:{}/keystone/v2.0/'.format(
                 self.swift_fixture.daemon_port),
             os_username=fakeswift.DEFAULT_USERNAME,
             os_password=fakeswift.DEFAULT_PASSWORD,
             os_tenant_name=fakeswift.DEFAULT_TENANT_NAME,
-            old_os_auth_url='http://localhost:{0}/keystone/v2.0/'.format(
+            old_os_auth_url='http://localhost:{}/keystone/v2.0/'.format(
                 old_swift_fixture.daemon_port),
             old_os_username=fakeswift.DEFAULT_USERNAME,
             old_os_password=fakeswift.DEFAULT_PASSWORD,
diff --git a/lib/lp/testing/tests/test_factory.py b/lib/lp/testing/tests/test_factory.py
index 500ab6b..61010aa 100644
--- a/lib/lp/testing/tests/test_factory.py
+++ b/lib/lp/testing/tests/test_factory.py
@@ -913,7 +913,7 @@ class IsSecurityProxiedOrHarmlessTests(TestCaseWithFactory):
             is_security_proxied_or_harmless([1, '2', proxied_person]))
         self.assertTrue(
             is_security_proxied_or_harmless(
-                set([1, '2', proxied_person])))
+                {1, '2', proxied_person}))
         self.assertTrue(
             is_security_proxied_or_harmless(
                 frozenset([1, '2', proxied_person])))
@@ -927,7 +927,7 @@ class IsSecurityProxiedOrHarmlessTests(TestCaseWithFactory):
             is_security_proxied_or_harmless([1, '2', unproxied_person]))
         self.assertFalse(
             is_security_proxied_or_harmless(
-                set([1, '2', unproxied_person])))
+                {1, '2', unproxied_person}))
         self.assertFalse(
             is_security_proxied_or_harmless(
                 frozenset([1, '2', unproxied_person])))
diff --git a/lib/lp/testing/tests/test_pages.py b/lib/lp/testing/tests/test_pages.py
index 1501fa0..d58a25e 100644
--- a/lib/lp/testing/tests/test_pages.py
+++ b/lib/lp/testing/tests/test_pages.py
@@ -43,4 +43,4 @@ class TestMakeStoryTest(unittest.TestCase):
 
         # Each unnumbered file appears as an independent test.
         ids = set(map(os.path.basename, map(methodcaller('id'), tests)))
-        self.assertEqual(set(['xx-bar.txt', 'xx-foo.txt']), ids)
+        self.assertEqual({'xx-bar.txt', 'xx-foo.txt'}, ids)
diff --git a/lib/lp/testing/tests/test_testcase.py b/lib/lp/testing/tests/test_testcase.py
index 4373901..75f5c26 100644
--- a/lib/lp/testing/tests/test_testcase.py
+++ b/lib/lp/testing/tests/test_testcase.py
@@ -84,7 +84,7 @@ class TestCaptureOops(TestCaseWithFactory):
         self.attachOopses()
         self.assertEqual(
             ["oops-0", "oops-1"],
-            sorted([a for a in self.getDetails() if "oops" in a]))
+            sorted(a for a in self.getDetails() if "oops" in a))
 
     def test_oops_content(self):
         self.assertEqual(0, len(self.oopses))
diff --git a/lib/lp/translations/browser/distroseries.py b/lib/lp/translations/browser/distroseries.py
index 7da5fe0..02a4292 100644
--- a/lib/lp/translations/browser/distroseries.py
+++ b/lib/lp/translations/browser/distroseries.py
@@ -231,7 +231,7 @@ class DistroSeriesView(LaunchpadView, TranslationsMixin):
         distroserieslangs = list(self.context.distroserieslanguages)
 
         # make a set of the existing languages
-        existing_languages = set([drl.language for drl in distroserieslangs])
+        existing_languages = {drl.language for drl in distroserieslangs}
 
         # find all the preferred languages which are not in the set of
         # existing languages, and add a dummydistroserieslanguage for each
diff --git a/lib/lp/translations/browser/person.py b/lib/lp/translations/browser/person.py
index 4d1120e..3b416da 100644
--- a/lib/lp/translations/browser/person.py
+++ b/lib/lp/translations/browser/person.py
@@ -68,9 +68,9 @@ class WorkListLinksAggregator(TranslationLinksAggregator):
     def describe(self, target, link, covered_files):
         """See `TranslationLinksAggregator.describe`."""
         strings_count = sum(
-            [self.countStrings(pofile) for pofile in covered_files])
-        languages = set(
-            [pofile.language.englishname for pofile in covered_files])
+            self.countStrings(pofile) for pofile in covered_files)
+        languages = {
+            pofile.language.englishname for pofile in covered_files}
         languages_list = ", ".join(sorted(languages))
 
         if strings_count == 1:
@@ -361,7 +361,7 @@ class PersonTranslationView(LaunchpadView):
         if remaining_slots <= 0:
             return existing_targets
 
-        known_targets = set([item['target'] for item in existing_targets])
+        known_targets = {item['target'] for item in existing_targets}
         really_new = [
             item
             for item in new_targets
diff --git a/lib/lp/translations/browser/productseries.py b/lib/lp/translations/browser/productseries.py
index 26dc765..0b9b00a 100644
--- a/lib/lp/translations/browser/productseries.py
+++ b/lib/lp/translations/browser/productseries.py
@@ -389,7 +389,7 @@ class ProductSeriesView(LaunchpadView,
         productserieslangs = list(self.context.productserieslanguages)
 
         # Make a set of the existing languages.
-        existing_languages = set(psl.language for psl in productserieslangs)
+        existing_languages = {psl.language for psl in productserieslangs}
 
         # Find all the preferred languages which are not in the set of
         # existing languages, and add a dummy PSL for each of them.
diff --git a/lib/lp/translations/browser/tests/test_persontranslationview.py b/lib/lp/translations/browser/tests/test_persontranslationview.py
index 4e17018..98ff0ba 100644
--- a/lib/lp/translations/browser/tests/test_persontranslationview.py
+++ b/lib/lp/translations/browser/tests/test_persontranslationview.py
@@ -174,7 +174,7 @@ class TestPersonTranslationView(TestCaseWithFactory):
         pofile_suffix = '/+translate?show=new_suggestions'
         expected_links = [canonical_url(pofile_worked_on) + pofile_suffix]
         self.assertEqual(
-            set(expected_links), set(item['link'] for item in targets))
+            set(expected_links), {item['link'] for item in targets})
 
     def test_recent_translation_activity(self):
         # the recent_activity property lists the most recent translation
@@ -217,7 +217,7 @@ class TestPersonTranslationView(TestCaseWithFactory):
         targets = self.view.top_projects_and_packages_to_review
 
         self.assertEqual(9, len(targets))
-        self.assertEqual(9, len(set(item['link'] for item in targets)))
+        self.assertEqual(9, len({item['link'] for item in targets}))
 
     def test_top_p_n_p_to_review_caps_total(self):
         # top_projects_and_packages will show at most 9 POFiles
@@ -228,7 +228,7 @@ class TestPersonTranslationView(TestCaseWithFactory):
         targets = self.view.top_projects_and_packages_to_review
 
         self.assertEqual(9, len(targets))
-        self.assertEqual(9, len(set(item['link'] for item in targets)))
+        self.assertEqual(9, len({item['link'] for item in targets}))
 
     def test_person_is_translator_false(self):
         # By default, a user is not a translator.
diff --git a/lib/lp/translations/browser/tests/test_potemplate_views.py b/lib/lp/translations/browser/tests/test_potemplate_views.py
index 00cf13b..78dc73b 100644
--- a/lib/lp/translations/browser/tests/test_potemplate_views.py
+++ b/lib/lp/translations/browser/tests/test_potemplate_views.py
@@ -47,8 +47,8 @@ class TestPOTemplateEditViewValidation(WithScenarios, TestCaseWithFactory):
         attributes = [
             'distroseries', 'sourcepackagename', 'productseries',
             'name', 'translation_domain']
-        data = dict(
-            [(name, getattr(potemplate, name)) for name in attributes])
+        data = {
+            name: getattr(potemplate, name) for name in attributes}
         data.update(**kwargs)
         return data
 
diff --git a/lib/lp/translations/browser/tests/test_translationmessage_view.py b/lib/lp/translations/browser/tests/test_translationmessage_view.py
index ea09ad1..3b7ecc0 100644
--- a/lib/lp/translations/browser/tests/test_translationmessage_view.py
+++ b/lib/lp/translations/browser/tests/test_translationmessage_view.py
@@ -416,8 +416,8 @@ class TestHelpers(TestCaseWithFactory):
 
     def test_revert_unselected_translations_handles_plurals(self):
         translated_forms = list(range(3))
-        translations = dict(
-            (form, self.getUniqueString()) for form in translated_forms)
+        translations = {
+            form: self.getUniqueString() for form in translated_forms}
 
         self.assertEqual(
             translations,
diff --git a/lib/lp/translations/browser/translationlinksaggregator.py b/lib/lp/translations/browser/translationlinksaggregator.py
index 89d0f49..d22ed82 100644
--- a/lib/lp/translations/browser/translationlinksaggregator.py
+++ b/lib/lp/translations/browser/translationlinksaggregator.py
@@ -92,7 +92,7 @@ class TranslationLinksAggregator:
 
         A template's language is None, which also counts.
         """
-        return len(set(self._getLanguage(sheet) for sheet in sheets))
+        return len({self._getLanguage(sheet) for sheet in sheets})
 
     def _circumscribe(self, sheets):
         """Find the best common UI link to cover all of `sheets`.
@@ -106,24 +106,24 @@ class TranslationLinksAggregator:
             # Simple case: one sheet.
             return {self._composeLink(first_sheet): sheets}
 
-        templates = set([self._getTemplate(sheet) for sheet in sheets])
+        templates = {self._getTemplate(sheet) for sheet in sheets}
 
-        productseries = set(
+        productseries = {
             template.productseries
             for template in templates
-            if template.productseries)
+            if template.productseries}
 
-        products = set(series.product for series in productseries)
+        products = {series.product for series in productseries}
 
-        sourcepackagenames = set(
+        sourcepackagenames = {
             template.sourcepackagename
             for template in templates
-            if template.sourcepackagename)
+            if template.sourcepackagename}
 
-        distroseries = set(
+        distroseries = {
             template.distroseries
             for template in templates
-            if template.sourcepackagename)
+            if template.sourcepackagename}
 
         assert len(products) <= 1, "Got more than one product."
         assert len(sourcepackagenames) <= 1, "Got more than one package."
@@ -165,8 +165,8 @@ class TranslationLinksAggregator:
         # Different release series of the same product.  Break down into
         # individual sheets.  We could try recursing here to get a better
         # set of aggregated links, but may not be worth the trouble.
-        return dict(
-            (self._composeLink(sheet), [sheet]) for sheet in sheets)
+        return {
+            self._composeLink(sheet): [sheet] for sheet in sheets}
 
     def aggregate(self, sheets):
         """Aggregate `sheets` into a list of translation target descriptions.
diff --git a/lib/lp/translations/browser/translationmessage.py b/lib/lp/translations/browser/translationmessage.py
index bc857cf..5087c92 100644
--- a/lib/lp/translations/browser/translationmessage.py
+++ b/lib/lp/translations/browser/translationmessage.py
@@ -1289,7 +1289,7 @@ class CurrentTranslationMessageView(LaunchpadView):
 
             alt_external = translations[self.sec_lang].used
             externally_used = sorted(
-                [m for m in translations[language].used if m.browser_pofile],
+                (m for m in translations[language].used if m.browser_pofile),
                 key=operator.attrgetter("date_created"),
                 reverse=True)
 
@@ -1297,8 +1297,8 @@ class CurrentTranslationMessageView(LaunchpadView):
             # translations for this same message in a different translation
             # template, but are not used.
             externally_suggested = sorted(
-                [m for m in translations[language].suggested
-                 if m.browser_pofile],
+                (m for m in translations[language].suggested
+                 if m.browser_pofile),
                 key=operator.attrgetter("date_created"),
                 reverse=True)
         else:
@@ -1333,7 +1333,7 @@ class CurrentTranslationMessageView(LaunchpadView):
         # Builds ITranslationMessageSuggestions for each type of the
         # suggestion per plural form.
         for index in self.pluralform_indices:
-            self.seen_translations = set([self.context.translations[index]])
+            self.seen_translations = {self.context.translations[index]}
             if other is not None:
                 self.seen_translations.add(other.translations[index])
             local_suggestions = (
diff --git a/lib/lp/translations/model/pofile.py b/lib/lp/translations/model/pofile.py
index afdb444..47d9d0e 100644
--- a/lib/lp/translations/model/pofile.py
+++ b/lib/lp/translations/model/pofile.py
@@ -1727,10 +1727,10 @@ class POFileToTranslationFileDataAdapter:
             msgset.file_references = row.file_references
 
             if row.flags_comment:
-                msgset.flags = set([
+                msgset.flags = {
                     flag.strip()
                     for flag in row.flags_comment.split(',')
-                    if flag])
+                    if flag}
 
             messages.append(msgset)
 
diff --git a/lib/lp/translations/model/pofiletranslator.py b/lib/lp/translations/model/pofiletranslator.py
index 2ded0d1..1be1643 100644
--- a/lib/lp/translations/model/pofiletranslator.py
+++ b/lib/lp/translations/model/pofiletranslator.py
@@ -51,7 +51,7 @@ class POFileTranslatorSet:
 
     def prefetchPOFileTranslatorRelations(self, pofiletranslators):
         """See `IPOFileTranslatorSet`."""
-        ids = set(record.id for record in pofiletranslators)
+        ids = {record.id for record in pofiletranslators}
         if not ids:
             return None
 
diff --git a/lib/lp/translations/model/potemplate.py b/lib/lp/translations/model/potemplate.py
index 45f6a99..bfef322 100644
--- a/lib/lp/translations/model/potemplate.py
+++ b/lib/lp/translations/model/potemplate.py
@@ -187,7 +187,7 @@ def get_pofiles_for(potemplates, language):
         POFile.potemplateID.is_in(template_ids),
         POFile.language == language))
 
-    mapping = dict((pofile.potemplate.id, pofile) for pofile in pofiles)
+    mapping = {pofile.potemplate.id: pofile for pofile in pofiles}
     result = [mapping.get(id) for id in template_ids]
     for entry, pofile in enumerate(result):
         assert pofile == result[entry], "This enumerate confuses me."
@@ -1624,10 +1624,10 @@ class POTemplateToTranslationFileDataAdapter:
             msgset.file_references = row.file_references
 
             if row.flags_comment:
-                msgset.flags = set([
+                msgset.flags = {
                     flag.strip()
                     for flag in row.flags_comment.split(',')
-                    if flag])
+                    if flag}
 
             # Store the message.
             messages.append(msgset)
diff --git a/lib/lp/translations/model/potmsgset.py b/lib/lp/translations/model/potmsgset.py
index c52e074..6e26c90 100644
--- a/lib/lp/translations/model/potmsgset.py
+++ b/lib/lp/translations/model/potmsgset.py
@@ -129,10 +129,10 @@ def dictify_translations(translations):
         # Turn a sequence into a dict.
         translations = dict(enumerate(translations))
     # Filter out None values.
-    return dict(
-        (form, translation)
+    return {
+        form: translation
         for form, translation in six.iteritems(translations)
-        if translation is not None)
+        if translation is not None}
 
 
 @implementer(IPOTMsgSet)
@@ -399,8 +399,8 @@ class POTMsgSet(SQLBase):
         # Present a list of language + usage constraints to sql. A language
         # can either be unconstrained, used, or suggested depending on which
         # of suggested_languages, used_languages it appears in.
-        suggested_languages = set(lang.id for lang in suggested_languages)
-        used_languages = set(lang.id for lang in used_languages)
+        suggested_languages = {lang.id for lang in suggested_languages}
+        used_languages = {lang.id for lang in used_languages}
         both_languages = suggested_languages.intersection(used_languages)
         suggested_languages = suggested_languages - both_languages
         used_languages = used_languages - both_languages
@@ -625,9 +625,9 @@ class POTMsgSet(SQLBase):
         if existing_message is not None:
             return existing_message
 
-        forms = dict(
-            ('msgstr%d' % form, potranslation)
-            for form, potranslation in six.iteritems(potranslations))
+        forms = {
+            'msgstr%d' % form: potranslation
+            for form, potranslation in six.iteritems(potranslations)}
 
         if from_import:
             origin = RosettaTranslationOrigin.SCM
@@ -762,9 +762,9 @@ class POTMsgSet(SQLBase):
         else:
             potemplate = None
 
-        translation_args = dict(
-            ('msgstr%d' % form, translation)
-            for form, translation in six.iteritems(translations))
+        translation_args = {
+            'msgstr%d' % form: translation
+            for form, translation in six.iteritems(translations)}
 
         return TranslationMessage(
             potmsgset=self,
diff --git a/lib/lp/translations/model/side.py b/lib/lp/translations/model/side.py
index 9c33602..49ee817 100644
--- a/lib/lp/translations/model/side.py
+++ b/lib/lp/translations/model/side.py
@@ -54,9 +54,9 @@ class TranslationSideTraitsSet:
             TranslationSide.UBUNTU, 'is_current_ubuntu', "Ubuntu")
         ubuntu.other_side_traits = upstream
         upstream.other_side_traits = ubuntu
-        self.traits = dict(
-            (traits.side, traits)
-            for traits in [ubuntu, upstream])
+        self.traits = {
+            traits.side: traits
+            for traits in [ubuntu, upstream]}
 
     def getTraits(self, side):
         """See `ITranslationSideTraitsSet`."""
diff --git a/lib/lp/translations/model/translationimportqueue.py b/lib/lp/translations/model/translationimportqueue.py
index 140292a..fac6387 100644
--- a/lib/lp/translations/model/translationimportqueue.py
+++ b/lib/lp/translations/model/translationimportqueue.py
@@ -144,8 +144,8 @@ def compose_approval_conflict_notice(domain, templates_count, sample):
         complete, just enough to report the problem usefully.
     :return: A string describing the problematic clash.
     """
-    sample_names = sorted([
-        '"%s"' % template.displayname for template in sample])
+    sample_names = sorted(
+        '"%s"' % template.displayname for template in sample)
     if templates_count > len(sample_names):
         sample_names.append("and more (not shown here)")
     return dedent("""\
diff --git a/lib/lp/translations/model/translationmessage.py b/lib/lp/translations/model/translationmessage.py
index 564cfa8..4d88020 100644
--- a/lib/lp/translations/model/translationmessage.py
+++ b/lib/lp/translations/model/translationmessage.py
@@ -601,9 +601,9 @@ class TranslationMessageSet:
             POFile.potemplateID == TranslationTemplateItem.potemplateID,
             *pofile_constraints
             ).config(distinct=(TranslationTemplateItem.potmsgsetID,))
-        potmsgset_map = dict(
-            (potmsgset_id, (pofile_id, sequence))
-            for potmsgset_id, pofile_id, sequence in results)
+        potmsgset_map = {
+            potmsgset_id: (pofile_id, sequence)
+            for potmsgset_id, pofile_id, sequence in results}
         load(POFile, (pofile_id for pofile_id, _ in potmsgset_map.values()))
         for message in messages:
             assert message.language == language
diff --git a/lib/lp/translations/scripts/scrub_pofiletranslator.py b/lib/lp/translations/scripts/scrub_pofiletranslator.py
index 91743e5..7094eba 100644
--- a/lib/lp/translations/scripts/scrub_pofiletranslator.py
+++ b/lib/lp/translations/scripts/scrub_pofiletranslator.py
@@ -64,7 +64,7 @@ def summarize_pofiles(pofile_ids):
     rows = store.find(
         (POFile.id, POFile.potemplateID, POFile.languageID),
         POFile.id.is_in(pofile_ids))
-    return dict((row[0], row[1:]) for row in rows)
+    return {row[0]: row[1:] for row in rows}
 
 
 def get_potmsgset_ids(potemplate_id):
@@ -240,7 +240,7 @@ def preload_work_items(work_items):
     productseries = load_related(
         ProductSeries, templates, ['productseriesID'])
     load_related(Product, productseries, ['productID'])
-    return dict((pofile.id, pofile) for pofile in pofiles)
+    return {pofile.id: pofile for pofile in pofiles}
 
 
 def process_work_items(logger, work_items, pofiles):
diff --git a/lib/lp/translations/scripts/tests/test_reupload_translations.py b/lib/lp/translations/scripts/tests/test_reupload_translations.py
index 73dc088..d8b43a7 100644
--- a/lib/lp/translations/scripts/tests/test_reupload_translations.py
+++ b/lib/lp/translations/scripts/tests/test_reupload_translations.py
@@ -80,7 +80,7 @@ def upload_tarball(translation_files):
 def summarize_translations_queue(sourcepackage):
     """Describe queue entries for `sourcepackage` as a name/contents dict."""
     entries = TranslationImportQueue().getAllEntries(sourcepackage)
-    return dict((entry.path, entry.content.read()) for entry in entries)
+    return {entry.path: entry.content.read() for entry in entries}
 
 
 def filter_paths(files_dict):
diff --git a/lib/lp/translations/scripts/tests/test_scrub_pofiletranslator.py b/lib/lp/translations/scripts/tests/test_scrub_pofiletranslator.py
index 7b80b0a..b36bac7 100644
--- a/lib/lp/translations/scripts/tests/test_scrub_pofiletranslator.py
+++ b/lib/lp/translations/scripts/tests/test_scrub_pofiletranslator.py
@@ -117,7 +117,7 @@ class TestScrubPOFileTranslator(TestCaseWithFactory):
         # way to avoid the risk of mistaking accidental orderings such
         # as per-id from being mistaken for the proper order.
         languages = ['nl', 'fr']
-        pofiles_per_language = dict((language, []) for language in languages)
+        pofiles_per_language = {language: [] for language in languages}
         for language, pofiles in pofiles_per_language.items():
             for template in templates:
                 pofiles.append(
@@ -244,7 +244,7 @@ class TestScrubPOFileTranslator(TestCaseWithFactory):
         old_poft = self.query_pofiletranslator(pofile, tm.submitter).one()
 
         fix_pofile(
-            fake_logger, pofile, [tm.potmsgset.id], set([tm.submitter.id]))
+            fake_logger, pofile, [tm.potmsgset.id], {tm.submitter.id})
 
         new_poft = self.query_pofiletranslator(pofile, tm.submitter).one()
         self.assertEqual(old_poft, new_poft)
@@ -255,7 +255,7 @@ class TestScrubPOFileTranslator(TestCaseWithFactory):
         self.becomeDbUser('postgres')
         poft = self.make_pofiletranslator_without_message()
         (pofile, person) = (poft.pofile, poft.person)
-        fix_pofile(fake_logger, pofile, [], set([person.id]))
+        fix_pofile(fake_logger, pofile, [], {person.id})
         self.assertIsNone(self.query_pofiletranslator(pofile, person).one())
 
     def test_fix_pofile_adds_missing_entries(self):
diff --git a/lib/lp/translations/scripts/tests/test_translations_import.py b/lib/lp/translations/scripts/tests/test_translations_import.py
index 0068508..07d8776 100644
--- a/lib/lp/translations/scripts/tests/test_translations_import.py
+++ b/lib/lp/translations/scripts/tests/test_translations_import.py
@@ -62,9 +62,9 @@ class TestTranslationsImport(TestCaseWithFactory):
 
     def _getEmailRecipients(self):
         """List the recipients of all pending outgoing emails."""
-        return sum([
+        return sum((
             recipients
-            for sender, recipients, text in stub.test_emails], [])
+            for sender, recipients, text in stub.test_emails), [])
 
     def test_describeEntry_without_target(self):
         productseries = self._makeProductSeries()
diff --git a/lib/lp/translations/tests/test_hastranslationtemplates.py b/lib/lp/translations/tests/test_hastranslationtemplates.py
index 3b13640..c3a0777 100644
--- a/lib/lp/translations/tests/test_hastranslationtemplates.py
+++ b/lib/lp/translations/tests/test_hastranslationtemplates.py
@@ -115,7 +115,7 @@ class HasTranslationTemplatesTestMixin:
         current_translations = set(
             self.container.getCurrentTranslationFiles())
         self.assertEqual(
-            set([pofile_sr, pofile_es]),
+            {pofile_sr, pofile_es},
             current_translations)
 
         # All files, no matter what template they are in, are returned.
@@ -124,7 +124,7 @@ class HasTranslationTemplatesTestMixin:
         current_translations = set(
             self.container.getCurrentTranslationFiles())
         self.assertEqual(
-            set([pofile_sr, pofile_es, pofile2_sr]),
+            {pofile_sr, pofile_es, pofile2_sr},
             current_translations)
 
         # If template is marked as obsolete, attached POFiles are
@@ -133,7 +133,7 @@ class HasTranslationTemplatesTestMixin:
         current_translations = set(
             self.container.getCurrentTranslationFiles())
         self.assertEqual(
-            set([pofile_sr, pofile_es]),
+            {pofile_sr, pofile_es},
             current_translations)
 
     def test_getCurrentTranslationFiles_ids(self):
@@ -144,7 +144,7 @@ class HasTranslationTemplatesTestMixin:
         current_translations_ids = set(
             self.container.getCurrentTranslationFiles(just_ids=True))
         self.assertEqual(
-            set([pofile_sr.id, pofile_es.id]),
+            {pofile_sr.id, pofile_es.id},
             current_translations_ids)
 
     def test_has_current_translation_templates__no_template(self):
diff --git a/lib/lp/translations/tests/test_potemplate.py b/lib/lp/translations/tests/test_potemplate.py
index 0212434..93a42fd 100644
--- a/lib/lp/translations/tests/test_potemplate.py
+++ b/lib/lp/translations/tests/test_potemplate.py
@@ -267,7 +267,7 @@ class TestProductTemplateEquivalenceClasses(TestCaseWithFactory,
             productseries=self.stable, name='foo-other')
 
         templates = set(list(self.subset.getSharingPOTemplates('foo')))
-        self.assertEqual(set([trunk_template, stable_template]), templates)
+        self.assertEqual({trunk_template, stable_template}, templates)
 
 
 class TestDistroTemplateEquivalenceClasses(TestCaseWithFactory,
@@ -380,7 +380,7 @@ class TestDistroTemplateEquivalenceClasses(TestCaseWithFactory,
             distribution=self.ubuntu, sourcepackagename=self.package)
 
         templates = set(list(subset.getSharingPOTemplates(template_name)))
-        self.assertEqual(set([warty_template, hoary_template]), templates)
+        self.assertEqual({warty_template, hoary_template}, templates)
 
     def test_GetSharingPOTemplates(self):
         # getSharingTemplates returns all sharing templates named foo.
@@ -1042,19 +1042,18 @@ class TestPOTemplateSubset(TestCaseWithFactory):
         domain = self.factory.getUniqueString()
         series = self.factory.makeProductSeries()
 
-        templates = dict(
-            (iscurrent, [self.factory.makePOTemplate(
+        templates = {
+            iscurrent: [self.factory.makePOTemplate(
                 translation_domain=domain, productseries=series,
-                iscurrent=iscurrent)])
-            for iscurrent in [False, True])
+                iscurrent=iscurrent)]
+            for iscurrent in [False, True]}
 
         potset = getUtility(IPOTemplateSet)
-        found_templates = dict((
-            iscurrent,
+        found_templates = {
+            iscurrent:
             list(potset.getSubset(productseries=series, iscurrent=iscurrent
                 ).getPOTemplatesByTranslationDomain(domain),)
-            )
-            for iscurrent in [False, True])
+            for iscurrent in [False, True]}
 
         self.assertEqual(templates, found_templates)
 
diff --git a/lib/lp/translations/tests/test_potmsgset.py b/lib/lp/translations/tests/test_potmsgset.py
index 5b59ebb..0a87230 100644
--- a/lib/lp/translations/tests/test_potmsgset.py
+++ b/lib/lp/translations/tests/test_potmsgset.py
@@ -1312,9 +1312,9 @@ class TestSetCurrentTranslation(TestCaseWithFactory):
 
     def _makeTranslations(self, potmsgset, forms=1):
         """Produce a POTranslations dict of random translations."""
-        return dict(
-            (form, self.factory.getUniqueString())
-            for form in range(forms))
+        return {
+            form: self.factory.getUniqueString()
+            for form in range(forms)}
 
     def test_baseline(self):
         # setCurrentTranslation sets the current translation
diff --git a/lib/lp/translations/tests/test_translationmerger.py b/lib/lp/translations/tests/test_translationmerger.py
index 733264e..1eb095b 100644
--- a/lib/lp/translations/tests/test_translationmerger.py
+++ b/lib/lp/translations/tests/test_translationmerger.py
@@ -363,7 +363,7 @@ class TestPOTMsgSetMergingAndTranslations(TestCaseWithFactory,
         # All three of the messages still exist, despite two of the
         # translations being near-identical.
         current_message, stable_message = self._getMessages()
-        expected_tms = set([current_message, trunk_message, stable_message])
+        expected_tms = {current_message, trunk_message, stable_message}
         tms = set(trunk_message.potmsgset.getAllTranslationMessages())
         self.assertEqual(tms, expected_tms)
         self.assertEqual(len(tms), 3)
@@ -536,7 +536,7 @@ class TestRemoveDuplicates(TestCaseWithFactory, TranslatedProductMixin):
         # stable has none.
         self.assertEqual(self._getTranslations(), ('snaggle', None))
         tms = set(potmsgset.getAllTranslationMessages())
-        self.assertEqual(tms, set([trunk_message, stable_message]))
+        self.assertEqual(tms, {trunk_message, stable_message})
 
         self.merger._removeDuplicateMessages()
 
diff --git a/lib/lp/translations/tests/test_translationpermission.py b/lib/lp/translations/tests/test_translationpermission.py
index 487b800..1a4ca94 100644
--- a/lib/lp/translations/tests/test_translationpermission.py
+++ b/lib/lp/translations/tests/test_translationpermission.py
@@ -129,9 +129,9 @@ class TestTranslationPermission(TestCaseWithFactory):
         potemplate = self.makePOTemplateForProduct(product)
         group = self.factory.makeTranslationGroup()
         potemplate.productseries.product.translationgroup = group
-        pofiles = dict(
-            (coverage, self.factory.makePOFile(potemplate=potemplate))
-            for coverage in team_coverage)
+        pofiles = {
+            coverage: self.factory.makePOFile(potemplate=potemplate)
+            for coverage in team_coverage}
         self.makeTranslationTeam(group, pofiles['tended'].language)
         self.makeTranslationTeam(
             group, pofiles['member'].language, members=[user])
diff --git a/lib/lp/translations/tests/test_translationtemplatesbuildbehaviour.py b/lib/lp/translations/tests/test_translationtemplatesbuildbehaviour.py
index e2b15a5..5bfd56d 100644
--- a/lib/lp/translations/tests/test_translationtemplatesbuildbehaviour.py
+++ b/lib/lp/translations/tests/test_translationtemplatesbuildbehaviour.py
@@ -272,7 +272,7 @@ class TestTranslationTemplatesBuildBehaviour(
                 'po-thethird/templ3.pot',
                 ]
             list1 = sorted(expected_templates)
-            list2 = sorted([entry.path for entry in entries])
+            list2 = sorted(entry.path for entry in entries)
             self.assertEqual(list1, list2)
 
         d.addCallback(got_status)
diff --git a/lib/lp/translations/utilities/translation_import.py b/lib/lp/translations/utilities/translation_import.py
index 59149de..ed5e79f 100644
--- a/lib/lp/translations/utilities/translation_import.py
+++ b/lib/lp/translations/utilities/translation_import.py
@@ -283,8 +283,8 @@ class TranslationImporter:
         """See `ITranslationImporter`."""
         # Several formats (particularly the various gettext variants) can have
         # the same template suffix.
-        unique_suffixes = set(
-            importer.template_suffix for importer in importers.values())
+        unique_suffixes = {
+            importer.template_suffix for importer in importers.values()}
         return sorted(unique_suffixes)
 
     def isTemplateName(self, path):
diff --git a/lib/lp/translations/utilities/translationmerger.py b/lib/lp/translations/utilities/translationmerger.py
index 28ec04d..524790f 100644
--- a/lib/lp/translations/utilities/translationmerger.py
+++ b/lib/lp/translations/utilities/translationmerger.py
@@ -101,7 +101,7 @@ def merge_translationtemplateitems(subordinate, representative,
     """
     source = subordinate.getAllTranslationTemplateItems()
     targets = representative.getAllTranslationTemplateItems()
-    templates = set(item.potemplate for item in targets)
+    templates = {item.potemplate for item in targets}
 
     for item in source:
         item = removeSecurityProxy(item)
@@ -497,7 +497,7 @@ class TranslationMerger:
             log.debug("Message %d/%d: %d subordinate(s)." % (
                 representative_num, num_representatives, len(potmsgsets)))
 
-            seen_potmsgsets = set([representative.id])
+            seen_potmsgsets = {representative.id}
 
             potmsgset_deletions = 0
             tm_deletions = 0
@@ -579,7 +579,7 @@ class TranslationMerger:
                 potmsgset = POTMsgSet.get(potmsgset_id)
 
                 tm_ids = self._partitionTranslationMessageIds(potmsgset)
-                before = sum([len(sublist) for sublist in tm_ids], 0)
+                before = sum((len(sublist) for sublist in tm_ids), 0)
 
                 for ids in tm_ids:
                     for id in ids:
@@ -607,9 +607,9 @@ class TranslationMerger:
         that's sorted out in the nested dicts).
         """
         tm = removeSecurityProxy(tm)
-        msgstr_ids = tuple([
+        msgstr_ids = tuple(
             getattr(tm, 'msgstr%d_id' % form)
-            for form in range(TranslationConstants.MAX_PLURAL_FORMS)])
+            for form in range(TranslationConstants.MAX_PLURAL_FORMS))
 
         return (tm.potemplateID, tm.languageID) + msgstr_ids
 
diff --git a/scripts/librarian-report.py b/scripts/librarian-report.py
index c8c75e7..f5c3b84 100755
--- a/scripts/librarian-report.py
+++ b/scripts/librarian-report.py
@@ -55,7 +55,7 @@ def main():
     cur = con.cursor()
 
     # Collect direct references to the LibraryFileAlias table.
-    references = set(
+    references = {
         (from_table, from_column)
         # Note that listReferences is recursive, which we don't
         # care about in this simple report. We also ignore the
@@ -63,7 +63,7 @@ def main():
         for from_table, from_column, to_table, to_column, update, delete
             in listReferences(cur, 'libraryfilealias', 'id')
         if to_table == 'libraryfilealias'
-        )
+        }
 
     totals = set()
     for referring_table, referring_column in sorted(references):
diff --git a/scripts/memcached-stats.py b/scripts/memcached-stats.py
index 002e90c..bc2c0cd 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 = dict((key, 0) for key in INTERESTING_KEYS)
+    totals = {key: 0 for key in INTERESTING_KEYS}
     for server, raw_stats in all_raw_stats:
         for key in INTERESTING_KEYS:
             totals[key] += int(raw_stats.get(key, 0))
diff --git a/test_on_merge.py b/test_on_merge.py
index 56aa4bc..19b5503 100755
--- a/test_on_merge.py
+++ b/test_on_merge.py
@@ -168,7 +168,7 @@ def run_test_process():
     # This keeps us from blocking when reading from a hung testrunner, allows
     # us to time out if the child process hangs, and avoids issues when using
     # Popen.communicate() with large data sets.
-    open_readers = set([xvfb_proc.stdout])
+    open_readers = {xvfb_proc.stdout}
     while open_readers:
         # select() blocks for a long time and can easily fail with EINTR
         # <https://bugs.launchpad.net/launchpad/+bug/615740>.  Really we
diff --git a/utilities/community-contributions.py b/utilities/community-contributions.py
index 7ca2e41..8080d94 100755
--- a/utilities/community-contributions.py
+++ b/utilities/community-contributions.py
@@ -316,8 +316,8 @@ merge_names_pairs = (
      u'William Grant <william.grant {_AT_} canonical.com>'),
     )
 # Then put it in dictionary form with the correct encodings.
-merge_names_map = dict((wiki_encode(a), wiki_encode(b))
-                       for a, b in merge_names_pairs)
+merge_names_map = {wiki_encode(a): wiki_encode(b)
+                       for a, b in merge_names_pairs}
 
 
 class ContainerRevision():
diff --git a/utilities/massage-bug-import-xml b/utilities/massage-bug-import-xml
index 5a304be..997e3dd 100755
--- a/utilities/massage-bug-import-xml
+++ b/utilities/massage-bug-import-xml
@@ -33,15 +33,15 @@ def truncate(text, message=None):
 
 
 def problem(message):
-    sys.stderr.write("{0}\n".format(message))
+    sys.stderr.write("{}\n".format(message))
 
 
 def problem_detail(message):
-    sys.stderr.write("  {0}\n".format(message))
+    sys.stderr.write("  {}\n".format(message))
 
 
 def problem_resolution(message):
-    sys.stderr.write("  --> {0}\n".format(message))
+    sys.stderr.write("  --> {}\n".format(message))
 
 
 def problem_resolved():
@@ -68,17 +68,17 @@ def massage(root, project_name, fix_nickname, tag_nickname):
 
     """
     # Resolve duplicates as far as they'll go.
-    duplicates = dict(
-        (node.getparent().get("id"), node.text)
+    duplicates = {
+        node.getparent().get("id"): node.text
         for node in root.findall('{%s}bug/{%s}duplicateof' % (NS, NS))
-        if node.text is not None and node.text.isdigit())
+        if node.text is not None and node.text.isdigit()}
 
     def resolve(bug_id):
         dupe_of = duplicates.get(bug_id)
         return (bug_id if dupe_of is None else resolve(dupe_of))
 
-    duplicates = dict(
-        (bug_id, resolve(bug_id)) for bug_id in duplicates)
+    duplicates = {
+        bug_id: resolve(bug_id) for bug_id in duplicates}
 
     # Scan the tree, fixing up issues.
     for bug in root.findall('{%s}bug' % NS):
diff --git a/utilities/roundup-sniffer.py b/utilities/roundup-sniffer.py
index b13b31e..5fbfb26 100755
--- a/utilities/roundup-sniffer.py
+++ b/utilities/roundup-sniffer.py
@@ -121,7 +121,7 @@ def get_distinct(things, fields):
     """
     def key(thing):
         return tuple(thing[field] for field in fields)
-    return dict((key(thing), thing) for thing in things)
+    return {key(thing): thing for thing in things}
 
 
 def gen_mapping(sniffer):