[PATCH 09/15] Replace dictionary iteration methods

Łukasz Żarnowiecki dolohow at outlook.com
Tue May 10 00:18:31 BST 2016


Signed-off-by: Łukasz Żarnowiecki <dolohow at outlook.com>
---
 offlineimap/accounts.py                 |  2 +-
 offlineimap/folder/Base.py              |  8 ++++----
 offlineimap/folder/GmailMaildir.py      | 10 +++++-----
 offlineimap/folder/LocalStatus.py       |  6 +++---
 offlineimap/folder/LocalStatusSQLite.py | 10 +++++-----
 offlineimap/folder/Maildir.py           |  6 +++---
 offlineimap/folder/UIDMaps.py           | 10 +++++-----
 offlineimap/imaplib2.py                 |  2 +-
 offlineimap/init.py                     | 12 ++++++------
 offlineimap/mbnames.py                  |  2 +-
 offlineimap/repository/Base.py          |  4 ++--
 offlineimap/repository/LocalStatus.py   |  4 ++--
 offlineimap/utils/stacktrace.py         |  2 +-
 test/tests/test_00_globals.py           |  2 +-
 14 files changed, 40 insertions(+), 40 deletions(-)

diff --git a/offlineimap/accounts.py b/offlineimap/accounts.py
index a8e8a5e..aa97ffe 100644
--- a/offlineimap/accounts.py
+++ b/offlineimap/accounts.py
@@ -483,7 +483,7 @@ def syncfolder(account, remotefolder, quick):
                 # the UID mapped case we want the actual local UIDs, not their
                 # remote counterparts
                 positive_uids = filter(
-                    lambda uid: uid > 0, partial.messagelist.keys())
+                    lambda uid: uid > 0, list(partial.messagelist.keys()))
                 if len(positive_uids) > 0:
                     min_uid = min(positive_uids)
                 else:
diff --git a/offlineimap/folder/Base.py b/offlineimap/folder/Base.py
index 06cf451..6243853 100644
--- a/offlineimap/folder/Base.py
+++ b/offlineimap/folder/Base.py
@@ -272,7 +272,7 @@ class BaseFolder(object):
     def ismessagelistempty(self):
         """Is the list of messages empty."""
 
-        if len(self.messagelist.keys()) < 1:
+        if len(list(self.messagelist.keys())) < 1:
             return True
         return False
 
@@ -307,7 +307,7 @@ class BaseFolder(object):
 
         You may have to call cachemessagelist() before calling this function!"""
 
-        return self.getmessagelist().keys()
+        return list(self.getmessagelist().keys())
 
     def getmessagecount(self):
         """Gets the number of messages."""
@@ -1009,14 +1009,14 @@ class BaseFolder(object):
                     delflaglist[flag] = []
                 delflaglist[flag].append(uid)
 
-        for flag, uids in addflaglist.items():
+        for flag, uids in list(addflaglist.items()):
             self.ui.addingflags(uids, flag, dstfolder)
             if self.repository.account.dryrun:
                 continue #don't actually add in a dryrun
             dstfolder.addmessagesflags(uids, set(flag))
             statusfolder.addmessagesflags(uids, set(flag))
 
-        for flag,uids in delflaglist.items():
+        for flag,uids in list(delflaglist.items()):
             self.ui.deletingflags(uids, flag, dstfolder)
             if self.repository.account.dryrun:
                 continue #don't actually remove in a dryrun
diff --git a/offlineimap/folder/GmailMaildir.py b/offlineimap/folder/GmailMaildir.py
index e184618..ea3c25c 100644
--- a/offlineimap/folder/GmailMaildir.py
+++ b/offlineimap/folder/GmailMaildir.py
@@ -48,11 +48,11 @@ class GmailMaildirFolder(MaildirFolder):
                 sorted(statusfolder.getmessageuidlist()):
             return True
         # check for flag changes, it's quick on a Maildir
-        for (uid, message) in self.getmessagelist().iteritems():
+        for (uid, message) in list(self.getmessagelist().items()):
             if message['flags'] != statusfolder.getmessageflags(uid):
                 return True
         # check for newer mtimes. it is also fast
-        for (uid, message) in self.getmessagelist().iteritems():
+        for (uid, message) in list(self.getmessagelist().items()):
             if message['mtime'] > statusfolder.getmessagemtime(uid):
                 return True
         return False  #Nope, nothing changed
@@ -70,7 +70,7 @@ class GmailMaildirFolder(MaildirFolder):
 
         # Get mtimes
         if self.synclabels:
-            for uid, msg in self.messagelist.items():
+            for uid, msg in list(self.messagelist.items()):
                 filepath = os.path.join(self.getfullname(), msg['filename'])
                 msg['mtime'] = int(os.stat(filepath).st_mtime)
 
@@ -284,7 +284,7 @@ class GmailMaildirFolder(MaildirFolder):
                         dellabellist[lb] = []
                     dellabellist[lb].append(uid)
 
-            for lb, uids in addlabellist.items():
+            for lb, uids in list(addlabellist.items()):
                 # bail out on CTRL-C or SIGTERM
                 if offlineimap.accounts.Account.abort_NOW_signal.is_set():
                     break
@@ -295,7 +295,7 @@ class GmailMaildirFolder(MaildirFolder):
                 dstfolder.addmessageslabels(uids, set([lb]))
                 statusfolder.addmessageslabels(uids, set([lb]))
 
-            for lb, uids in dellabellist.items():
+            for lb, uids in list(dellabellist.items()):
                 # bail out on CTRL-C or SIGTERM
                 if offlineimap.accounts.Account.abort_NOW_signal.is_set():
                     break
diff --git a/offlineimap/folder/LocalStatus.py b/offlineimap/folder/LocalStatus.py
index 4171569..e3eb40b 100644
--- a/offlineimap/folder/LocalStatus.py
+++ b/offlineimap/folder/LocalStatus.py
@@ -168,7 +168,7 @@ class LocalStatusFolder(BaseFolder):
         with self.savelock:
             cachefd = open(self.filename + ".tmp", "wt")
             cachefd.write((self.magicline % self.cur_version) + "\n")
-            for msg in self.messagelist.values():
+            for msg in list(self.messagelist.values()):
                 flags = ''.join(sorted(msg['flags']))
                 labels = ', '.join(sorted(msg['labels']))
                 cachefd.write("%s|%s|%d|%s\n" % (msg['uid'], flags, msg['mtime'], labels))
@@ -228,7 +228,7 @@ class LocalStatusFolder(BaseFolder):
     def savemessageslabelsbulk(self, labels):
         """Saves labels from a dictionary in a single database operation."""
 
-        for uid, lb in labels.items():
+        for uid, lb in list(labels.items()):
             self.messagelist[uid]['labels'] = lb
         self.save()
 
@@ -248,7 +248,7 @@ class LocalStatusFolder(BaseFolder):
     def savemessagesmtimebulk(self, mtimes):
         """Saves mtimes from the mtimes dictionary in a single database operation."""
 
-        for uid, mt in mtimes.items():
+        for uid, mt in list(mtimes.items()):
             self.messagelist[uid]['mtime'] = mt
         self.save()
 
diff --git a/offlineimap/folder/LocalStatusSQLite.py b/offlineimap/folder/LocalStatusSQLite.py
index d7d8472..e1e63e5 100644
--- a/offlineimap/folder/LocalStatusSQLite.py
+++ b/offlineimap/folder/LocalStatusSQLite.py
@@ -236,7 +236,7 @@ class LocalStatusSQLiteFolder(BaseFolder):
         """Saves the entire messagelist to the database."""
 
         data = []
-        for uid, msg in self.messagelist.items():
+        for uid, msg in list(self.messagelist.items()):
             mtime = msg['mtime']
             flags = ''.join(sorted(msg['flags']))
             labels = ', '.join(sorted(msg['labels']))
@@ -337,9 +337,9 @@ class LocalStatusSQLiteFolder(BaseFolder):
         Saves labels from a dictionary in a single database operation.
 
         """
-        data = [(', '.join(sorted(l)), uid) for uid, l in labels.items()]
+        data = [(', '.join(sorted(l)), uid) for uid, l in list(labels.items())]
         self.__sql_write('UPDATE status SET labels=? WHERE id=?', data, executemany=True)
-        for uid, l in labels.items():
+        for uid, l in list(labels.items()):
             self.messagelist[uid]['labels'] = l
 
 
@@ -370,9 +370,9 @@ class LocalStatusSQLiteFolder(BaseFolder):
     def savemessagesmtimebulk(self, mtimes):
         """Saves mtimes from the mtimes dictionary in a single database operation."""
 
-        data = [(mt, uid) for uid, mt in mtimes.items()]
+        data = [(mt, uid) for uid, mt in list(mtimes.items())]
         self.__sql_write('UPDATE status SET mtime=? WHERE id=?', data, executemany=True)
-        for uid, mt in mtimes.items():
+        for uid, mt in list(mtimes.items()):
             self.messagelist[uid]['mtime'] = mt
 
 
diff --git a/offlineimap/folder/Maildir.py b/offlineimap/folder/Maildir.py
index f1e4c17..ac6908a 100644
--- a/offlineimap/folder/Maildir.py
+++ b/offlineimap/folder/Maildir.py
@@ -207,7 +207,7 @@ class MaildirFolder(BaseFolder):
             positive_uids = filter(lambda uid: uid > 0, retval)
             if positive_uids:
                 min_uid = min(positive_uids)
-                for uid in date_excludees.keys():
+                for uid in list(date_excludees.keys()):
                     if uid > min_uid:
                         # This message was originally excluded because of
                         # its date. It is re-included now because we want all
@@ -225,7 +225,7 @@ class MaildirFolder(BaseFolder):
                 sorted(statusfolder.getmessageuidlist()):
             return True
         # Also check for flag changes, it's quick on a Maildir.
-        for (uid, message) in self.getmessagelist().iteritems():
+        for (uid, message) in list(self.getmessagelist().items()):
             if message['flags'] != statusfolder.getmessageflags(uid):
                 return True
         return False  # Nope, nothing changed.
@@ -489,7 +489,7 @@ class MaildirFolder(BaseFolder):
         """
         oldfmd5 = md5(self.name).hexdigest()
         msglist = self._scanfolder()
-        for mkey, mvalue in msglist.iteritems():
+        for mkey, mvalue in list(msglist.items()):
             filename = os.path.join(self.getfullname(), mvalue['filename'])
             match = re.search("FMD5=([a-fA-F0-9]+)", filename)
             if match is None:
diff --git a/offlineimap/folder/UIDMaps.py b/offlineimap/folder/UIDMaps.py
index 31db369..20318ae 100644
--- a/offlineimap/folder/UIDMaps.py
+++ b/offlineimap/folder/UIDMaps.py
@@ -77,7 +77,7 @@ class MappedIMAPFolder(IMAPFolder):
         if dolock: self.maplock.acquire()
         try:
             file = open(mapfilename + ".tmp", 'wt')
-            for (key, value) in self.diskl2r.iteritems():
+            for (key, value) in list(self.diskl2r.items()):
                 file.write("%d:%d\n"% (key, value))
             file.close()
             os.rename(mapfilename + '.tmp', mapfilename)
@@ -104,7 +104,7 @@ class MappedIMAPFolder(IMAPFolder):
             # OK.  Now we've got a nice list.  First, delete things from the
             # summary that have been deleted from the folder.
 
-            for luid in self.diskl2r.keys():
+            for luid in list(self.diskl2r.keys()):
                 if not luid in reallist:
                     ruid = self.diskl2r[luid]
                     del self.diskr2l[ruid]
@@ -117,7 +117,7 @@ class MappedIMAPFolder(IMAPFolder):
             self.r2l = self.diskr2l.copy()
             self.l2r = self.diskl2r.copy()
 
-            for luid in reallist.keys():
+            for luid in list(reallist.keys()):
                 if not luid in self.l2r:
                     ruid = nextneg
                     nextneg -= 1
@@ -142,7 +142,7 @@ class MappedIMAPFolder(IMAPFolder):
         You may have to call cachemessagelist() before calling this function!"""
         # This implementation overrides the one in BaseFolder, as it is
         # much more efficient for the mapped case.
-        return self.r2l.keys()
+        return list(self.r2l.keys())
 
     # Interface from BaseFolder
     def getmessagecount(self):
@@ -162,7 +162,7 @@ class MappedIMAPFolder(IMAPFolder):
         localhash = self._mb.getmessagelist()
         self.maplock.acquire()
         try:
-            for key, value in localhash.items():
+            for key, value in list(localhash.items()):
                 try:
                     key = self.l2r[key]
                 except KeyError:
diff --git a/offlineimap/imaplib2.py b/offlineimap/imaplib2.py
index 61878f6..2ff06c1 100755
--- a/offlineimap/imaplib2.py
+++ b/offlineimap/imaplib2.py
@@ -1818,7 +1818,7 @@ class IMAP4(object):
                 select.POLLHUP:     'Hang up',
                 select.POLLNVAL:    'Invalid request: descriptor not open',
             }
-            return ' '.join([PollErrors[s] for s in PollErrors.keys() if (s & state)])
+            return ' '.join([PollErrors[s] for s in list(PollErrors.keys()) if (s & state)])
 
         if bytes != str:
             line_part = b''
diff --git a/offlineimap/init.py b/offlineimap/init.py
index 6803fd8..65b8391 100644
--- a/offlineimap/init.py
+++ b/offlineimap/init.py
@@ -190,7 +190,7 @@ class OfflineImap:
             ui_type = ui_type.split('.')[-1]
             # TODO, make use of chosen ui for logging
             logging.warning('Using old interface name, consider using one '
-                            'of %s'% ', '.join(UI_LIST.keys()))
+                            'of %s'% ', '.join(list(UI_LIST.keys())))
         if options.diagnostics: ui_type = 'basic' # enforce basic UI for --info
 
         # dry-run? Set [general]dry-run=True
@@ -203,7 +203,7 @@ class OfflineImap:
             self.ui = UI_LIST[ui_type.lower()](config)
         except KeyError:
             logging.error("UI '%s' does not exist, choose one of: %s"% \
-                              (ui_type, ', '.join(UI_LIST.keys())))
+                              (ui_type, ', '.join(list(UI_LIST.keys()))))
             sys.exit(1)
         setglobalui(self.ui)
 
@@ -291,10 +291,10 @@ class OfflineImap:
             d = collections.defaultdict(lambda: 0)
             for v in l:
                 d[tuple(v)] += 1
-            return list((k, v) for k, v in d.iteritems())
+            return list((k, v) for k, v in list(d.items()))
 
         stack_displays = []
-        for threadId, stack in sys._current_frames().items():
+        for threadId, stack in list(sys._current_frames().items()):
             stack_display = []
             for filename, lineno, name, line in traceback.extract_stack(stack):
                 stack_display.append('  File: "%s", line %d, in %s'
@@ -315,7 +315,7 @@ class OfflineImap:
             self.ui.debug('thread', msg % (times, '\n'.join(stack[- (context * 2):])))
 
         self.ui.debug('thread', "Dumped a total of %d Threads." %
-                      len(sys._current_frames().keys()))
+                      len(list(sys._current_frames().keys())))
 
 
     def __sync(self, options):
@@ -342,7 +342,7 @@ class OfflineImap:
                     else:
                         errormsg = "The account '%s' does not exist.  Valid ac" \
                             "counts are: %s"% \
-                            (account, ", ".join(allaccounts.keys()))
+                            (account, ", ".join(list(allaccounts.keys())))
                     self.ui.terminate(1, errormsg=errormsg)
                 if account not in syncaccounts:
                     syncaccounts.append(account)
diff --git a/offlineimap/mbnames.py b/offlineimap/mbnames.py
index 8829ee5..9b109e1 100644
--- a/offlineimap/mbnames.py
+++ b/offlineimap/mbnames.py
@@ -78,7 +78,7 @@ def __genmbnames():
             mb_sort_keyfunc = localeval.eval(config.get("mbnames", "sort_keyfunc"),
                                          {'re': re})
         itemlist = []
-        for accountname in boxes.keys():
+        for accountname in list(boxes.keys()):
             localroot = localroots[accountname]
             for foldername in boxes[accountname]:
                 if folderfilter(accountname, foldername):
diff --git a/offlineimap/repository/Base.py b/offlineimap/repository/Base.py
index e3f1cc9..9711e25 100644
--- a/offlineimap/repository/Base.py
+++ b/offlineimap/repository/Base.py
@@ -190,7 +190,7 @@ class BaseRepository(CustomConfig.ConfigHelperMixin, object):
                     dst_repo.getsep(), src_repo.getsep())] = folder
 
         # Find and create new folders on src_repo.
-        for src_name_t, src_folder in src_hash.iteritems():
+        for src_name_t, src_folder in list(src_hash.items()):
             # Don't create on dst_repo, if it is readonly.
             if not dst_repo.get_create_folders():
                 break
@@ -207,7 +207,7 @@ class BaseRepository(CustomConfig.ConfigHelperMixin, object):
                 status_repo.makefolder(src_name_t.replace(dst_repo.getsep(),
                                                    status_repo.getsep()))
         # Find and create new folders on dst_repo.
-        for dst_name_t, dst_folder in dst_hash.iteritems():
+        for dst_name_t, dst_folder in list(dst_hash.items()):
             if not src_repo.get_create_folders():
                 # Don't create missing folder on readonly repo.
                 break
diff --git a/offlineimap/repository/LocalStatus.py b/offlineimap/repository/LocalStatus.py
index 25fadc0..a1b14ea 100644
--- a/offlineimap/repository/LocalStatus.py
+++ b/offlineimap/repository/LocalStatus.py
@@ -50,7 +50,7 @@ class LocalStatusRepository(BaseRepository):
         return self.LocalStatusFolderClass(foldername, self) # Instanciate.
 
     def setup_backend(self, backend):
-        if backend in self.backends.keys():
+        if backend in list(self.backends.keys()):
             self._backend = backend
             self.root = self.backends[backend]['root']
             self.LocalStatusFolderClass = self.backends[backend]['class']
@@ -60,7 +60,7 @@ class LocalStatusRepository(BaseRepository):
                 (backend, self.account.name))
 
     def import_other_backend(self, folder):
-        for bk, dic in self.backends.items():
+        for bk, dic in list(self.backends.items()):
             # skip folder's own type
             if dic['class'] == type(folder):
                 continue
diff --git a/offlineimap/utils/stacktrace.py b/offlineimap/utils/stacktrace.py
index 7c885b0..007d7ec 100644
--- a/offlineimap/utils/stacktrace.py
+++ b/offlineimap/utils/stacktrace.py
@@ -13,7 +13,7 @@ def dump(out):
 	for th in threading.enumerate():
 		id2name[th.ident] = th.name
 	n = 0
-	for i, stack in sys._current_frames().items():
+	for i, stack in list(sys._current_frames().items()):
 		out.write ("\n# Thread #%d (id=%d), %s\n" % \
 		  (n, i, id2name[i]))
 		n = n + 1
diff --git a/test/tests/test_00_globals.py b/test/tests/test_00_globals.py
index b4572f9..7775fb0 100755
--- a/test/tests/test_00_globals.py
+++ b/test/tests/test_00_globals.py
@@ -19,7 +19,7 @@ class TestOfflineimapGlobals(unittest.TestCase):
 		globals.set_options (klass.o)
 
 	def test_initial_state(self):
-		for k in self.o.__dict__.keys():
+		for k in list(self.o.__dict__.keys()):
 			self.assertTrue(getattr(self.o, k) ==
 			  getattr(globals.options, k))
 
-- 
2.8.2





More information about the OfflineIMAP-project mailing list