[PATCH 1/9] Make the iter*() dictionary methods Python 3 compatible (#1014220)

Martin Kolman mkolman at redhat.com
Wed Jan 28 17:43:15 UTC 2015


Python 3 deprecates the iteritems(),
iterkeys() and itervalues()) methods and instead makes
the items(), keys() and values() methods returns an iterator.

This makes the affected dictionaries Python 3 compatible,
while still preserving Python 2 compatibility at a cost
of slight memory usage increase and/or slight slowdown.

Signed-off-by: Martin Kolman <mkolman at redhat.com>
---
 pyanaconda/addons.py                       | 6 +++---
 pyanaconda/anaconda.py                     | 2 +-
 pyanaconda/anaconda_argparse.py            | 4 ++--
 pyanaconda/kickstart.py                    | 2 +-
 pyanaconda/localization.py                 | 2 +-
 pyanaconda/packaging/dnfpayload.py         | 4 ++--
 pyanaconda/threads.py                      | 2 +-
 pyanaconda/ui/__init__.py                  | 4 ++--
 pyanaconda/ui/gui/hubs/__init__.py         | 2 +-
 pyanaconda/ui/gui/spokes/custom.py         | 6 +++---
 pyanaconda/ui/gui/spokes/datetime_spoke.py | 2 +-
 pyanaconda/ui/gui/spokes/lib/resize.py     | 2 +-
 pyanaconda/ui/gui/spokes/source.py         | 2 +-
 pyanaconda/ui/gui/spokes/storage.py        | 4 ++--
 pyanaconda/ui/gui/xkl_wrapper.py           | 4 ++--
 pyanaconda/ui/tui/hubs/__init__.py         | 4 ++--
 pyanaconda/ui/tui/spokes/time_spoke.py     | 3 +--
 scripts/makeupdates                        | 2 +-
 tests/pyanaconda_tests/ks_version_test.py  | 4 ++--
 tests/pyanaconda_tests/timezone_test.py    | 4 ++--
 20 files changed, 32 insertions(+), 33 deletions(-)

diff --git a/pyanaconda/addons.py b/pyanaconda/addons.py
index 5083167..e01eb4a 100644
--- a/pyanaconda/addons.py
+++ b/pyanaconda/addons.py
@@ -75,17 +75,17 @@ class AddonRegistry(object):
 
     def __str__(self):
         return functools.reduce(lambda acc, (id, addon): acc + str(addon),
-                                self.__dict__.iteritems(), "")
+                                iter(self.__dict__.items()), "")
 
     def execute(self, storage, ksdata, instClass, users):
         """This method calls execute on all the registered addons."""
-        for v in self.__dict__.itervalues():
+        for v in self.__dict__.values():
             if hasattr(v, "execute"):
                 v.execute(storage, ksdata, instClass, users)
 
     def setup(self, storage, ksdata, instClass):
         """This method calls setup on all the registered addons."""
-        for v in self.__dict__.itervalues():
+        for v in self.__dict__.values():
             if hasattr(v, "setup"):
                 v.setup(storage, ksdata, instClass)
 
diff --git a/pyanaconda/anaconda.py b/pyanaconda/anaconda.py
index 7592650..cb4138d 100644
--- a/pyanaconda/anaconda.py
+++ b/pyanaconda/anaconda.py
@@ -188,7 +188,7 @@ class Anaconda(object):
 
         # gather up info on the running threads
         threads = "\nThreads\n-------\n"
-        for thread_id, frame in sys._current_frames().iteritems():
+        for thread_id, frame in sys._current_frames().items():
             threads += "\nThread %s\n" % (thread_id,)
             threads += "".join(format_stack(frame))
 
diff --git a/pyanaconda/anaconda_argparse.py b/pyanaconda/anaconda_argparse.py
index c7ac77f..5c85213 100644
--- a/pyanaconda/anaconda_argparse.py
+++ b/pyanaconda/anaconda_argparse.py
@@ -161,7 +161,7 @@ class AnacondaArgumentParser(ArgumentParser):
         according to the option definitions set by add_argument.
 
         boot_cmdline can be given as a string (to be parsed by BootArgs), or a
-        dict (or any object with .iteritems()) of {bootarg:value} pairs.
+        dict (or any object with .items()) of {bootarg:value} pairs.
 
         If boot_cmdline is None, the boot_cmdline data will be whatever BootArgs reads
         by default (/proc/cmdline, /run/initramfs/etc/cmdline, /etc/cmdline).
@@ -186,7 +186,7 @@ class AnacondaArgumentParser(ArgumentParser):
         # go over all options corresponding to current boot cmdline
         # and do any modifications necessary
         # NOTE: program cmdline overrides boot cmdline
-        for arg, val in bootargs.iteritems():
+        for arg, val in bootargs.items():
             option = self._get_bootarg_option(arg)
             if option is None:
                 # this boot option is unknown to Anaconda, skip it
diff --git a/pyanaconda/kickstart.py b/pyanaconda/kickstart.py
index 49c8613..5701eff 100644
--- a/pyanaconda/kickstart.py
+++ b/pyanaconda/kickstart.py
@@ -1080,7 +1080,7 @@ class PartitionData(commands.partition.F18_PartData):
         storage.doAutoPart = False
 
         if self.onbiosdisk != "":
-            for (disk, biosdisk) in storage.eddDict.iteritems():
+            for (disk, biosdisk) in storage.eddDict.items():
                 if "%x" % biosdisk == self.onbiosdisk:
                     self.disk = disk
                     break
diff --git a/pyanaconda/localization.py b/pyanaconda/localization.py
index a7cc908..350365d 100644
--- a/pyanaconda/localization.py
+++ b/pyanaconda/localization.py
@@ -152,7 +152,7 @@ def find_best_locale_match(locale, langcodes):
         if not locale_parts or not langcode_parts:
             return score
 
-        for part, part_score in score_map.iteritems():
+        for part, part_score in score_map.items():
             if locale_parts[part] and langcode_parts[part]:
                 if locale_parts[part] == langcode_parts[part]:
                     # match
diff --git a/pyanaconda/packaging/dnfpayload.py b/pyanaconda/packaging/dnfpayload.py
index 0fd3ac3..136772a 100644
--- a/pyanaconda/packaging/dnfpayload.py
+++ b/pyanaconda/packaging/dnfpayload.py
@@ -110,7 +110,7 @@ def _pick_mpoint(df, requested):
     if not len(sufficients):
         return None
     # default to the biggest one:
-    return sorted(sufficients.iteritems(), key=operator.itemgetter(1),
+    return sorted(sufficients.items(), key=operator.itemgetter(1),
                   reverse=True)[0][0]
 
 class PayloadRPMDisplay(dnf.callback.LoggingTransactionDisplay):
@@ -741,7 +741,7 @@ class DNFPayload(packaging.PackagePayload):
                 return
 
             # Otherwise, fall back to the default repos that we disabled above
-            for (id_, repo) in self._base.repos.iteritems():
+            for (id_, repo) in self._base.repos.items():
                 if id_ in enabled:
                     repo.enable()
 
diff --git a/pyanaconda/threads.py b/pyanaconda/threads.py
index f116593..a06f134 100644
--- a/pyanaconda/threads.py
+++ b/pyanaconda/threads.py
@@ -121,7 +121,7 @@ class ThreadManager(object):
             self.wait(name)
 
         if self.any_errors:
-            thread_names = ", ".join(thread_name for thread_name in self._errors.iterkeys()
+            thread_names = ", ".join(thread_name for thread_name in self._errors.keys()
                                      if self._errors[thread_name])
             msg = "Unhandled errors from the following threads detected: %s" % thread_names
             raise RuntimeError(msg)
diff --git a/pyanaconda/ui/__init__.py b/pyanaconda/ui/__init__.py
index b7353af..9bf7959 100644
--- a/pyanaconda/ui/__init__.py
+++ b/pyanaconda/ui/__init__.py
@@ -28,7 +28,7 @@ class PathDict(dict):
     """Dictionary class supporting + operator"""
     def __add__(self, ext):
         new_dict = copy.copy(self)
-        for key, value in ext.iteritems():
+        for key, value in ext.items():
             try:
                 new_dict[key].extend(value)
             except KeyError:
@@ -82,7 +82,7 @@ class UserInterface(object):
     def update_paths(cls, pathdict):
         """Receives pathdict and appends it's contents to the current
            class defined search path dictionary."""
-        for k,v in pathdict.iteritems():
+        for k,v in pathdict.items():
             cls.paths.setdefault(k, [])
             cls.paths[k].extend(v)
 
diff --git a/pyanaconda/ui/gui/hubs/__init__.py b/pyanaconda/ui/gui/hubs/__init__.py
index 7da5888..30769ec 100644
--- a/pyanaconda/ui/gui/hubs/__init__.py
+++ b/pyanaconda/ui/gui/hubs/__init__.py
@@ -368,7 +368,7 @@ class Hub(GUIObject, common.Hub):
         self._inSpoke = False
 
         # Now update the selector with the current status and completeness.
-        for sp in self._spokes.itervalues():
+        for sp in self._spokes.values():
             if not sp.indirect:
                 self._updateCompleteness(sp, update_continue=False)
 
diff --git a/pyanaconda/ui/gui/spokes/custom.py b/pyanaconda/ui/gui/spokes/custom.py
index c051055..9fc42d6 100644
--- a/pyanaconda/ui/gui/spokes/custom.py
+++ b/pyanaconda/ui/gui/spokes/custom.py
@@ -290,7 +290,7 @@ class CustomPartitioningSpoke(NormalSpoke, StorageChecker):
             Restrict the set to ones that we might allow users to select.
         """
         _fs_types = []
-        for cls in device_formats.itervalues():
+        for cls in device_formats.values():
             obj = cls()
 
             # btrfs is always handled by on_device_type_changed
@@ -511,7 +511,7 @@ class CustomPartitioningSpoke(NormalSpoke, StorageChecker):
 
             page = Page(root.name)
 
-            for (mountpoint, device) in root.mounts.iteritems():
+            for (mountpoint, device) in root.mounts.items():
                 if device not in self._devices or \
                    not device.disks or \
                    (root.name != translated_new_install_name() and not device.format.exists):
@@ -1396,7 +1396,7 @@ class CustomPartitioningSpoke(NormalSpoke, StorageChecker):
 
         device_type = devicefactory.get_device_type(device)
 
-        for _type in self._device_name_dict.iterkeys():
+        for _type in self._device_name_dict.keys():
             if _type == device_type:
                 self._device_name_dict[_type] = device_name
                 continue
diff --git a/pyanaconda/ui/gui/spokes/datetime_spoke.py b/pyanaconda/ui/gui/spokes/datetime_spoke.py
index 1648c35..3bf9d56 100644
--- a/pyanaconda/ui/gui/spokes/datetime_spoke.py
+++ b/pyanaconda/ui/gui/spokes/datetime_spoke.py
@@ -490,7 +490,7 @@ class DatetimeSpoke(FirstbootSpokeMixIn, NormalSpoke):
 
         cities = set()
         xlated_regions = ((region, get_xlated_timezone(region))
-                          for region in self._regions_zones.iterkeys())
+                          for region in self._regions_zones.keys())
         for region, xlated in sorted(xlated_regions, cmp=_compare_regions):
             self.add_to_store_xlated(self._regionsStore, region, xlated)
             for city in self._regions_zones[region]:
diff --git a/pyanaconda/ui/gui/spokes/lib/resize.py b/pyanaconda/ui/gui/spokes/lib/resize.py
index 0f52f22..740e40e 100644
--- a/pyanaconda/ui/gui/spokes/lib/resize.py
+++ b/pyanaconda/ui/gui/spokes/lib/resize.py
@@ -95,7 +95,7 @@ class ResizeDialog(GUIObject):
         # First, try to find the partition in some known Root.  If we find
         # it, return the mountpoint as the description.
         for root in self.storage.roots:
-            for (mount, device) in root.mounts.iteritems():
+            for (mount, device) in root.mounts.items():
                 if device == part:
                     return "%s (%s)" % (mount, root.name)
 
diff --git a/pyanaconda/ui/gui/spokes/source.py b/pyanaconda/ui/gui/spokes/source.py
index 3a04c47..1b35ca9 100644
--- a/pyanaconda/ui/gui/spokes/source.py
+++ b/pyanaconda/ui/gui/spokes/source.py
@@ -1225,7 +1225,7 @@ class SourceSpoke(NormalSpoke, GUISpokeInputCheckHandler):
                 self._repoMirrorlistCheckbox.set_active(False)
 
         if url:
-            for idx, proto in REPO_PROTO.iteritems():
+            for idx, proto in REPO_PROTO.items():
                 if url.startswith(proto):
                     self._repoProtocolComboBox.set_active_id(idx)
                     self._repoUrlEntry.set_text(url[len(proto):])
diff --git a/pyanaconda/ui/gui/spokes/storage.py b/pyanaconda/ui/gui/spokes/storage.py
index 455c394..88f1a8a 100644
--- a/pyanaconda/ui/gui/spokes/storage.py
+++ b/pyanaconda/ui/gui/spokes/storage.py
@@ -790,8 +790,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.values())
+            fs_free = sum(f[1] for f in free_space.values())
 
         required_space = self.payload.spaceRequired
         auto_swap = sum((r.size for r in self.storage.autoPartitionRequests
diff --git a/pyanaconda/ui/gui/xkl_wrapper.py b/pyanaconda/ui/gui/xkl_wrapper.py
index 1f7855b..d970ce1 100644
--- a/pyanaconda/ui/gui/xkl_wrapper.py
+++ b/pyanaconda/ui/gui/xkl_wrapper.py
@@ -197,12 +197,12 @@ class XklWrapper(object):
     def get_available_layouts(self):
         """A generator yielding layouts (no need to store them as a bunch)"""
 
-        return self._layout_infos.iterkeys()
+        return self._layout_infos.keys()
 
     def get_switching_options(self):
         """Method returning list of available layout switching options"""
 
-        return self._switch_opt_infos.iterkeys()
+        return self._switch_opt_infos.keys()
 
     def get_layout_variant_description(self, layout_variant, with_lang=True, xlated=True):
         """
diff --git a/pyanaconda/ui/tui/hubs/__init__.py b/pyanaconda/ui/tui/hubs/__init__.py
index e89bf71..7605dca 100644
--- a/pyanaconda/ui/tui/hubs/__init__.py
+++ b/pyanaconda/ui/tui/hubs/__init__.py
@@ -87,8 +87,8 @@ class TUIHub(TUIObject, common.Hub):
             return tui.ColumnWidget([(3, [number]), (None, [w])], 1)
 
         # split spokes to two columns
-        left = [_prep(i, w) for i,w in self._keys.iteritems() if i % 2 == 1]
-        right = [_prep(i, w) for i,w in self._keys.iteritems() if i % 2 == 0]
+        left = [_prep(i, w) for i,w in self._keys.items() if i % 2 == 1]
+        right = [_prep(i, w) for i,w in self._keys.items() if i % 2 == 0]
 
         c = tui.ColumnWidget([(39, left), (39, right)], 2)
         self._window.append(c)
diff --git a/pyanaconda/ui/tui/spokes/time_spoke.py b/pyanaconda/ui/tui/spokes/time_spoke.py
index a6e59e3..a1a4b4b 100644
--- a/pyanaconda/ui/tui/spokes/time_spoke.py
+++ b/pyanaconda/ui/tui/spokes/time_spoke.py
@@ -39,8 +39,7 @@ class TimeZoneSpoke(FirstbootSpokeMixIn, NormalTUISpoke):
         # needs to be unsorted in order to display in the same order as the GUI
         # so whatever
         self._regions = timezone.get_all_regions_and_timezones().keys()
-        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().items())
         self._lower_regions = [r.lower() for r in self._timezones]
 
         self._zones = ["%s/%s" % (region, z) for region in self._timezones for z in self._timezones[region]]
diff --git a/scripts/makeupdates b/scripts/makeupdates
index ab420e3..633b93c 100755
--- a/scripts/makeupdates
+++ b/scripts/makeupdates
@@ -782,7 +782,7 @@ def get_RPMs_from_koji(packages, fedora_number, arch):
 
     index = 1
     print("starting %d worker threads" % len(packages))
-    for _package_name, package in packages.iteritems():
+    for _package_name, package in packages.items():
         thread = threading.Thread(name=index, target=get_rpm_from_Koji_thread,
                                   args=(package, fedora_number,
                                         arch, rpm_paths, print_lock))
diff --git a/tests/pyanaconda_tests/ks_version_test.py b/tests/pyanaconda_tests/ks_version_test.py
index 84fa384..2b8e25c 100644
--- a/tests/pyanaconda_tests/ks_version_test.py
+++ b/tests/pyanaconda_tests/ks_version_test.py
@@ -40,7 +40,7 @@ class BaseTestCase(unittest.TestCase):
 class CommandVersionTestCase(BaseTestCase):
     def commands_test(self):
         """Test that anaconda uses the right versions of kickstart commands"""
-        for (commandName, commandObj) in self._commandMap.iteritems():
+        for (commandName, commandObj) in self._commandMap.items():
             pykickstartClass = self.handler.commands[commandName].__class__
             self.assertIsInstance(commandObj(), pykickstartClass)
 
@@ -48,7 +48,7 @@ class CommandVersionTestCase(BaseTestCase):
 class DataVersionTestCase(BaseTestCase):
     def data_test(self):
         """Test that anaconda uses the right versions of kickstart data"""
-        for (dataName, dataObj) in self._dataMap.iteritems():
+        for (dataName, dataObj) in self._dataMap.items():
             # pykickstart does not expose data objects as a mapping the way
             # it does command objects.
             pykickstartClass = eval("self.handler.%s" % dataName)
diff --git a/tests/pyanaconda_tests/timezone_test.py b/tests/pyanaconda_tests/timezone_test.py
index 26084d5..00c1520 100644
--- a/tests/pyanaconda_tests/timezone_test.py
+++ b/tests/pyanaconda_tests/timezone_test.py
@@ -25,7 +25,7 @@ import mock
 class TimezonesListings(unittest.TestCase):
     def string_timezones_test(self):
         """Check if returned timezones are plain strings, not unicode objects."""
-        for (region, zones) in timezone.get_all_regions_and_timezones().iteritems():
+        for (region, zones) in timezone.get_all_regions_and_timezones().items():
             self.assertIsInstance(region, str)
 
             for zone in zones:
@@ -34,7 +34,7 @@ class TimezonesListings(unittest.TestCase):
     def all_timezones_valid_test(self):
         """Check if all returned timezones are considered valid timezones."""
 
-        for (region, zones) in timezone.get_all_regions_and_timezones().iteritems():
+        for (region, zones) in timezone.get_all_regions_and_timezones().items():
             for zone in zones:
                 self.assertTrue(timezone.is_valid_timezone(region + "/" + zone))
 
-- 
2.1.0



More information about the anaconda-patches mailing list