[PATCH] Don't create temporary lists if not needed

Vratislav Podzimek vpodzime at redhat.com
Thu Mar 14 13:21:07 UTC 2013


In many cases generators can be used instead of constructing temporary lists.
Some functions even support the generator expresions passed directly as
arguments.

Signed-off-by: Vratislav Podzimek <vpodzime at redhat.com>
---
 pyanaconda/anaconda_optparse.py      |  2 +-
 pyanaconda/bootloader.py             |  4 ++--
 pyanaconda/iutil.py                  |  2 +-
 pyanaconda/kickstart.py              |  4 ++--
 pyanaconda/network.py                |  2 +-
 pyanaconda/packaging/__init__.py     |  2 +-
 pyanaconda/packaging/tarpayload.py   |  2 +-
 pyanaconda/packaging/yumpayload.py   |  4 ++--
 pyanaconda/simpleconfig.py           |  2 +-
 pyanaconda/ui/gui/spokes/custom.py   | 18 +++++++++---------
 pyanaconda/ui/gui/spokes/network.py  |  4 ++--
 pyanaconda/ui/gui/spokes/storage.py  | 14 +++++++-------
 pyanaconda/ui/gui/spokes/user.py     |  4 ++--
 pyanaconda/ui/tui/simpleline/base.py |  2 +-
 pyanaconda/ui/tui/spokes/__init__.py |  2 +-
 pyanaconda/ui/tui/spokes/time.py     |  2 +-
 16 files changed, 35 insertions(+), 35 deletions(-)

diff --git a/pyanaconda/anaconda_optparse.py b/pyanaconda/anaconda_optparse.py
index ccb0361..37f4b86 100644
--- a/pyanaconda/anaconda_optparse.py
+++ b/pyanaconda/anaconda_optparse.py
@@ -57,7 +57,7 @@ class AnacondaOptionParser(OptionParser):
         bootargs = [a for a in args if not a.startswith('-')]
         do_bootarg = kwargs.pop("bootarg", True)
         option = OptionParser.add_option(self, *flags, **kwargs)
-        bootargs += [flag[2:] for flag in option._long_opts]
+        bootargs += (flag[2:] for flag in option._long_opts)
         if do_bootarg:
             for b in bootargs:
                 if b in self._boot_arg:
diff --git a/pyanaconda/bootloader.py b/pyanaconda/bootloader.py
index a802ca8..fae6db8 100644
--- a/pyanaconda/bootloader.py
+++ b/pyanaconda/bootloader.py
@@ -346,7 +346,7 @@ class BootLoader(object):
     def images(self):
         """ List of OS images that will be included in the configuration. """
         all_images = self.linux_images
-        all_images.extend([i for i in self.chain_images if i.label])
+        all_images.extend(i for i in self.chain_images if i.label)
         return all_images
 
     def clear_images(self):
@@ -1084,7 +1084,7 @@ class GRUB(BootLoader):
         salt_chars = string.letters + string.digits + './'
 
         rand_gen = random.SystemRandom()
-        salt += "".join([rand_gen.choice(salt_chars) for i in range(salt_len)])
+        salt += "".join(rand_gen.choice(salt_chars) for i in range(salt_len))
         self.encrypted_password = crypt.crypt(self.password, salt)
 
     def write_config_password(self, config):
diff --git a/pyanaconda/iutil.py b/pyanaconda/iutil.py
index 05e7753..9db998e 100644
--- a/pyanaconda/iutil.py
+++ b/pyanaconda/iutil.py
@@ -475,7 +475,7 @@ class ProxyString(object):
         """
         components = ["url", "noauth_url", "protocol", "host", "port",
                       "username", "password"]
-        return dict([(k, getattr(self, k)) for k in components]) 
+        return dict((k, getattr(self, k)) for k in components)
 
     def __str__(self):
         return self.url
diff --git a/pyanaconda/kickstart.py b/pyanaconda/kickstart.py
index b41d198..a6f2405 100644
--- a/pyanaconda/kickstart.py
+++ b/pyanaconda/kickstart.py
@@ -1095,7 +1095,7 @@ class RaidData(commands.raid.F18_RaidData):
             removeExistingFormat(device, storage)
             devicetree.registerAction(ActionCreateFormat(device, kwargs["format"]))
         else:
-            if devicename and devicename in [a.name for a in storage.mdarrays]:
+            if devicename and devicename in (a.name for a in storage.mdarrays):
                 raise KickstartValueError(formatErrorMsg(self.lineno, msg="The Software RAID array name \"%s\" is already in use." % devicename))
 
             # If a previous device has claimed this mount point, delete the
@@ -1287,7 +1287,7 @@ class VolGroupData(commands.volgroup.FC16_VolGroupData):
             dev = devicetree.getDeviceByName(self.vgname)
             if not dev:
                 raise KickstartValueError, formatErrorMsg(self.lineno, msg="No preexisting VG with the name \"%s\" was found." % self.vgname)
-        elif self.vgname in [vg.name for vg in storage.vgs]:
+        elif self.vgname in (vg.name for vg in storage.vgs):
             raise KickstartValueError(formatErrorMsg(self.lineno, msg="The volume group name \"%s\" is already in use." % self.vgname))
         else:
             request = storage.newVG(parents=pvs,
diff --git a/pyanaconda/network.py b/pyanaconda/network.py
index 626e2c0..27da1bf 100644
--- a/pyanaconda/network.py
+++ b/pyanaconda/network.py
@@ -268,7 +268,7 @@ class NetworkDevice(IfcfgFile):
     def set(self, *args):
         # If we are changing value of a key set _dirty flag
         # informing that ifcfg file needs to be synced.
-        s = " ".join(["%s=%s" % key_val for key_val in args])
+        s = " ".join("%s=%s" % key_val for key_val in args)
         ifcfglog.debug("NetworkDevice %s set: %s" %
                        (self.iface, s))
         for (key, data) in args:
diff --git a/pyanaconda/packaging/__init__.py b/pyanaconda/packaging/__init__.py
index cba0f79..1904a3e 100644
--- a/pyanaconda/packaging/__init__.py
+++ b/pyanaconda/packaging/__init__.py
@@ -163,7 +163,7 @@ class Payload(object):
             urls.extend(repo.mirrorlist)
         network_protocols = ["http:", "ftp:", "nfs:", "nfsiso:"]
         for url in urls:
-            if any([url.startswith(p) for p in network_protocols]):
+            if any(url.startswith(p) for p in network_protocols):
                 return True
 
         return False
diff --git a/pyanaconda/packaging/tarpayload.py b/pyanaconda/packaging/tarpayload.py
index 32361d8..26922af 100644
--- a/pyanaconda/packaging/tarpayload.py
+++ b/pyanaconda/packaging/tarpayload.py
@@ -69,7 +69,7 @@ class TarPayload(ArchivePayload):
 
     @property
     def requiredSpace(self):
-        byte_count = sum([m.size for m in self.archive.getmembers()])
+        byte_count = sum(m.size for m in self.archive.getmembers())
         return byte_count / (1024.0 * 1024.0)   # FIXME: Size
 
     @property
diff --git a/pyanaconda/packaging/yumpayload.py b/pyanaconda/packaging/yumpayload.py
index fe132f7..0119470 100644
--- a/pyanaconda/packaging/yumpayload.py
+++ b/pyanaconda/packaging/yumpayload.py
@@ -354,7 +354,7 @@ reposdir=%s
 
         # trigger setup of self._yum.config
         log.debug("installation yum config repos: %s"
-                  % ",".join([r.id for r in self._yum.repos.listEnabled()]))
+                  % ",".join(r.id for r in self._yum.repos.listEnabled()))
 
     # YUMFIXME: there should be a way to reset package sacks without all this
     #           knowledge of the yum internals or, better yet, some convenience
@@ -511,7 +511,7 @@ reposdir=%s
                     self.disableRepo(repo.id)
                 elif self.data.method.method and \
                      repo.id != BASE_REPO_NAME and \
-                     repo.id not in [r.name for r in self.data.repo.dataList()]:
+                     repo.id not in (r.name for r in self.data.repo.dataList()):
                     # if a method/repo was given, disable all default repos
                     self.disableRepo(repo.id)
 
diff --git a/pyanaconda/simpleconfig.py b/pyanaconda/simpleconfig.py
index 9fb1289..66b38b0 100644
--- a/pyanaconda/simpleconfig.py
+++ b/pyanaconda/simpleconfig.py
@@ -107,7 +107,7 @@ class SimpleConfigFile(object):
            self.info[uppercase_ASCII_string(key)] = value
 
     def unset(self, *keys):
-        for key in [uppercase_ASCII_string(k) for k in keys]:
+        for key in (uppercase_ASCII_string(k) for k in keys):
             if key in self.info:
                del self.info[key]
 
diff --git a/pyanaconda/ui/gui/spokes/custom.py b/pyanaconda/ui/gui/spokes/custom.py
index 3e19707..4140ac9 100644
--- a/pyanaconda/ui/gui/spokes/custom.py
+++ b/pyanaconda/ui/gui/spokes/custom.py
@@ -573,7 +573,7 @@ class CustomPartitioningSpoke(NormalSpoke, StorageChecker):
 
     def _setCurrentFreeSpace(self):
         """Add up all the free space on selected disks and return it as a Size."""
-        self._free_space = sum([f[0] for f in self._currentFreeInfo.values()])
+        self._free_space = sum(f[0] for f in self._currentFreeInfo.values())
 
     def _currentTotalSpace(self):
         """Add up the sizes of all selected disks and return it as a Size."""
@@ -703,8 +703,8 @@ class CustomPartitioningSpoke(NormalSpoke, StorageChecker):
             label.set_text(self._when_create_text % (productName, productVersion))
         else:
             swaps = [d for d in new_devices if d.format.type == "swap"]
-            mounts = dict([(d.format.mountpoint, d) for d in new_devices
-                                if getattr(d.format, "mountpoint", None)])
+            mounts = dict((d.format.mountpoint, d) for d in new_devices
+                                if getattr(d.format, "mountpoint", None))
 
             for device in new_devices:
                 if device in self.bootLoaderDevices:
@@ -828,7 +828,7 @@ class CustomPartitioningSpoke(NormalSpoke, StorageChecker):
 
         if selector:
             # newest device should be the one with the highest id
-            max_id = max([d.id for d in self._devices])
+            max_id = max(d.id for d in self._devices)
 
             # update the selector with the new device and its size
             selectorFromDevice(self.__storage.devicetree.getDeviceByID(max_id),
@@ -1456,7 +1456,7 @@ class CustomPartitioningSpoke(NormalSpoke, StorageChecker):
         encryptCheckbox.set_sensitive(self._reformatCheckbox.get_active())
         ancestors = use_dev.ancestors
         ancestors.remove(use_dev)
-        if any([a.format.type == "luks" and a.format.exists for a in ancestors]):
+        if any(a.format.type == "luks" and a.format.exists for a in ancestors):
             # The encryption checkbutton should not be sensitive if there is
             # existing encryption below the leaf layer.
             encryptCheckbox.set_sensitive(False)
@@ -1606,9 +1606,9 @@ class CustomPartitioningSpoke(NormalSpoke, StorageChecker):
     def on_finish_clicked(self, button):
         self._save_right_side(self._current_selector)
 
-        new_luks = any([d for d in self.__storage.devices
+        new_luks = any(d for d in self.__storage.devices
                             if d.format.type == "luks" and
-                               not d.format.exists])
+                               not d.format.exists)
         if new_luks:
             dialog = PassphraseDialog(self.data)
             with enlightbox(self.window, dialog.window):
@@ -1873,7 +1873,7 @@ class CustomPartitioningSpoke(NormalSpoke, StorageChecker):
                     return
 
             if dialog.deleteAll:
-                for dev in [s._device for s in page.members]:
+                for dev in (s._device for s in page.members):
                     self._destroy_device(dev)
             else:
                 self._destroy_device(device)
@@ -2181,7 +2181,7 @@ class CustomPartitioningSpoke(NormalSpoke, StorageChecker):
 
             ancestors = device.ancestors
             ancestors.remove(device)
-            if any([a.format.type == "luks" and a.format.exists for a in ancestors]):
+            if any(a.format.type == "luks" and a.format.exists for a in ancestors):
                 # The encryption checkbutton should not be sensitive if there is
                 # existing encryption below the leaf layer.
                 encryption_checkbutton.set_sensitive(False)
diff --git a/pyanaconda/ui/gui/spokes/network.py b/pyanaconda/ui/gui/spokes/network.py
index 8fee6c3..2046987 100644
--- a/pyanaconda/ui/gui/spokes/network.py
+++ b/pyanaconda/ui/gui/spokes/network.py
@@ -694,8 +694,8 @@ class NetworkControlBox(object):
             addr = socket.inet_ntoa(struct.pack('=L',
                                                 ipv4cfg.get_addresses()[0].get_address()))
             self._set_device_info_value(dt, "ipv4", addr)
-            dnss = " ".join([socket.inet_ntoa(struct.pack('=L', addr))
-                             for addr in ipv4cfg.get_nameservers()])
+            dnss = " ".join(socket.inet_ntoa(struct.pack('=L', addr))
+                             for addr in ipv4cfg.get_nameservers())
             self._set_device_info_value(dt, "dns", dnss)
             gateway = socket.inet_ntoa(struct.pack('=L',
                                                    ipv4cfg.get_addresses()[0].get_gateway()))
diff --git a/pyanaconda/ui/gui/spokes/storage.py b/pyanaconda/ui/gui/spokes/storage.py
index 1b474f0..0890f1c 100644
--- a/pyanaconda/ui/gui/spokes/storage.py
+++ b/pyanaconda/ui/gui/spokes/storage.py
@@ -381,9 +381,9 @@ class StorageSpoke(NormalSpoke, StorageChecker):
 
     def _applyDiskSelection(self, use_names):
         onlyuse = use_names[:]
-        for disk in [d for d in self.storage.disks if d.name in onlyuse]:
-            onlyuse.extend([d.name for d in disk.ancestors
-                                        if d.name not in onlyuse])
+        for disk in (d for d in self.storage.disks if d.name in onlyuse):
+            onlyuse.extend(d.name for d in disk.ancestors
+                           if d.name not in onlyuse)
 
         self.data.ignoredisk.onlyuse = onlyuse
         self.data.clearpart.drives = use_names[:]
@@ -730,8 +730,8 @@ class StorageSpoke(NormalSpoke, StorageChecker):
         # Figure out if the existing disk labels will work on this platform
         # you need to have at least one of the platform's labels in order for
         # any of the free space to be useful.
-        disk_labels = set([disk.format.labelType for disk in disks \
-                                                 if hasattr(disk.format, "labelType")])
+        disk_labels = set(disk.format.labelType for disk in disks \
+                              if hasattr(disk.format, "labelType"))
         platform_labels = set(platform.diskLabelTypes)
         if disk_labels and platform_labels.isdisjoint(disk_labels):
             disk_free = 0
@@ -741,8 +741,8 @@ class StorageSpoke(NormalSpoke, StorageChecker):
         else:
             free_space = self.storage.getFreeSpace(disks=disks,
                                                    clearPartType=CLEARPART_TYPE_NONE)
-            disk_free = sum([f[0] for f in free_space.itervalues()])
-            fs_free = sum([f[1] for f in free_space.itervalues()])
+            disk_free = sum(f[0] for f in free_space.itervalues())
+            fs_free = sum(f[1] for f in free_space.itervalues())
 
         required_space = self.payload.spaceRequired
         auto_swap = Size(bytes=0)
diff --git a/pyanaconda/ui/gui/spokes/user.py b/pyanaconda/ui/gui/spokes/user.py
index af39856..66d1232 100644
--- a/pyanaconda/ui/gui/spokes/user.py
+++ b/pyanaconda/ui/gui/spokes/user.py
@@ -264,8 +264,8 @@ class UserSpoke(FirstbootSpokeMixIn, NormalSpoke):
                  self._wheel.name in self._user.groups:
                 self._user.groups.remove(self._wheel.name)
 
-            self.data.group.groupList += [self._groupDict[g] for g in self._user.groups
-                                                             if g != self._wheel.name]
+            self.data.group.groupList += (self._groupDict[g] for g in self._user.groups
+                                                             if g != self._wheel.name)
 
             if self._user not in self.data.user.userList:
                 self.data.user.userList.append(self._user)
diff --git a/pyanaconda/ui/tui/simpleline/base.py b/pyanaconda/ui/tui/simpleline/base.py
index 131a54a..df1f6f0 100644
--- a/pyanaconda/ui/tui/simpleline/base.py
+++ b/pyanaconda/ui/tui/simpleline/base.py
@@ -602,7 +602,7 @@ class Widget(object):
 
     def __unicode__(self):
         """Method to render the screen when printing as unicode string."""
-        return u"\n".join([u"".join(l) for l in self._buffer])
+        return u"\n".join(u"".join(l) for l in self._buffer)
 
     def setxy(self, row, col):
         """Sets cursor position.
diff --git a/pyanaconda/ui/tui/spokes/__init__.py b/pyanaconda/ui/tui/spokes/__init__.py
index e4d7d33..87c05ac 100644
--- a/pyanaconda/ui/tui/spokes/__init__.py
+++ b/pyanaconda/ui/tui/spokes/__init__.py
@@ -96,5 +96,5 @@ def collect_categories(mask_paths):
     for mask, path in mask_paths:
         classes.extend(collect(mask, path, lambda obj: hasattr(obj, "category") and obj.category != None and obj.category != ""))
         
-    categories = set([c.category for c in classes])
+    categories = set(c.category for c in classes)
     return categories
diff --git a/pyanaconda/ui/tui/spokes/time.py b/pyanaconda/ui/tui/spokes/time.py
index 6a47401..290a9bf 100644
--- a/pyanaconda/ui/tui/spokes/time.py
+++ b/pyanaconda/ui/tui/spokes/time.py
@@ -34,7 +34,7 @@ class TimeZoneSpoke(NormalTUISpoke):
         NormalTUISpoke.__init__(self, app, data, storage, payload, instclass)
 
     def initialize(self):
-        self._timezones = dict([(k, sorted(v)) for k,v in timezone.get_all_regions_and_timezones().iteritems()])
+        self._timezones = dict((k, sorted(v)) for k,v in timezone.get_all_regions_and_timezones().iteritems())
         self._regions = [r for r in self._timezones]
         self._lower_regions = [r.lower() for r in self._timezones]
 
-- 
1.7.11.7



More information about the anaconda-patches mailing list