From edb052c53a9742165bea263604a651a865c669b5 2010-10-10 20:08:49
From: Thomas Kluyver <takowl@gmail.com>
Date: 2010-10-10 20:08:49
Subject: [PATCH] Replacing some .items() calls with .iteritems() for cleaner conversion with 2to3.

---

diff --git a/IPython/__init__.py b/IPython/__init__.py
index 2a0bc8d..0f7b866 100755
--- a/IPython/__init__.py
+++ b/IPython/__init__.py
@@ -47,7 +47,7 @@ from .testing import test
 
 # Release data
 __author__ = ''
-for author, email in release.authors.values():
+for author, email in release.authors.itervalues():
     __author__ += author + ' <' + email + '>\n'
 __license__  = release.license
 __version__  = release.version
diff --git a/IPython/config/configurable.py b/IPython/config/configurable.py
index 18cb050..ed8fc2a 100755
--- a/IPython/config/configurable.py
+++ b/IPython/config/configurable.py
@@ -112,7 +112,7 @@ class Configurable(HasTraits):
             # dynamically create the section with name self.__class__.__name__.
             if new._has_section(sname):
                 my_config = new[sname]
-                for k, v in traits.items():
+                for k, v in traits.iteritems():
                     # Don't allow traitlets with config=True to start with
                     # uppercase.  Otherwise, they are confused with Config
                     # subsections.  But, developers shouldn't have uppercase
diff --git a/IPython/config/loader.py b/IPython/config/loader.py
index 5800fd5..33f7deb 100644
--- a/IPython/config/loader.py
+++ b/IPython/config/loader.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
 # coding: utf-8
 """A simple configuration system.
 
@@ -73,7 +74,7 @@ class Config(dict):
 
     def _merge(self, other):
         to_update = {}
-        for k, v in other.items():
+        for k, v in other.iteritems():
             if not self.has_key(k):
                 to_update[k] = v
             else: # I have this key
@@ -365,7 +366,7 @@ class ArgParseConfigLoader(CommandLineConfigLoader):
 
     def _convert_to_config(self):
         """self.parsed_data->self.config"""
-        for k, v in vars(self.parsed_data).items():
+        for k, v in vars(self.parsed_data).iteritems():
             exec_str = 'self.config.' + k + '= v'
             exec exec_str in locals(), globals()
 
diff --git a/IPython/core/completerlib.py b/IPython/core/completerlib.py
index 23ad50c..95f0e4b 100644
--- a/IPython/core/completerlib.py
+++ b/IPython/core/completerlib.py
@@ -336,7 +336,7 @@ def cd_completer(self, event):
             return [compress_user(relpath, tilde_expand, tilde_val)]
 
         # if no completions so far, try bookmarks
-        bks = self.db.get('bookmarks',{}).keys()
+        bks = self.db.get('bookmarks',{}).iterkeys()
         bkmatches = [s for s in bks if s.startswith(event.symbol)]
         if bkmatches:
             return bkmatches
diff --git a/IPython/core/history.py b/IPython/core/history.py
index 8be2c49..39ebd3c 100644
--- a/IPython/core/history.py
+++ b/IPython/core/history.py
@@ -260,7 +260,7 @@ class ShadowHist(object):
     
     def all(self):
         d = self.db.hdict('shadowhist')
-        items = [(i,s) for (s,i) in d.items()]
+        items = [(i,s) for (s,i) in d.iteritems()]
         items.sort()
         return items
 
diff --git a/IPython/core/interactiveshell.py b/IPython/core/interactiveshell.py
index 4e63a87..d4b28c9 100644
--- a/IPython/core/interactiveshell.py
+++ b/IPython/core/interactiveshell.py
@@ -511,7 +511,7 @@ class InteractiveShell(Configurable, Magic):
     def restore_sys_module_state(self):
         """Restore the state of the sys module."""
         try:
-            for k, v in self._orig_sys_module_state.items():
+            for k, v in self._orig_sys_module_state.iteritems():
                 setattr(sys, k, v)
         except AttributeError:
             pass
diff --git a/IPython/core/tests/test_inputsplitter.py b/IPython/core/tests/test_inputsplitter.py
index fd2dbfc..685ca1f 100644
--- a/IPython/core/tests/test_inputsplitter.py
+++ b/IPython/core/tests/test_inputsplitter.py
@@ -356,7 +356,7 @@ class InteractiveLoopTestCase(unittest.TestCase):
         # We can't check that the provided ns is identical to the test_ns,
         # because Python fills test_ns with extra keys (copyright, etc).  But
         # we can check that the given dict is *contained* in test_ns
-        for k,v in ns.items():
+        for k,v in ns.iteritems():
             self.assertEqual(test_ns[k], v)
         
     def test_simple(self):
diff --git a/IPython/core/tests/test_magic.py b/IPython/core/tests/test_magic.py
index 72f5fa1..d15af47 100644
--- a/IPython/core/tests/test_magic.py
+++ b/IPython/core/tests/test_magic.py
@@ -33,7 +33,7 @@ def test_rehashx():
     # Practically ALL ipython development systems will have more than 10 aliases
 
     yield (nt.assert_true, len(_ip.alias_manager.alias_table) > 10)
-    for key, val in _ip.alias_manager.alias_table.items():
+    for key, val in _ip.alias_manager.alias_table.iteritems():
         # we must strip dots from alias names
         nt.assert_true('.' not in key)
 
diff --git a/IPython/external/configobj.py b/IPython/external/configobj.py
index 9e64f18..303f10b 100644
--- a/IPython/external/configobj.py
+++ b/IPython/external/configobj.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
 # configobj.py
 # A config file reader/writer that supports nested sections in config files.
 # Copyright (C) 2005-2008 Michael Foord, Nicola Larosa
@@ -32,22 +33,7 @@ except ImportError:
     pass
 from types import StringTypes
 from warnings import warn
-try:
-    from codecs import BOM_UTF8, BOM_UTF16, BOM_UTF16_BE, BOM_UTF16_LE
-except ImportError:
-    # Python 2.2 does not have these
-    # UTF-8
-    BOM_UTF8 = '\xef\xbb\xbf'
-    # UTF-16, little endian
-    BOM_UTF16_LE = '\xff\xfe'
-    # UTF-16, big endian
-    BOM_UTF16_BE = '\xfe\xff'
-    if sys.byteorder == 'little':
-        # UTF-16, native endianness
-        BOM_UTF16 = BOM_UTF16_LE
-    else:
-        # UTF-16, native endianness
-        BOM_UTF16 = BOM_UTF16_BE
+from codecs import BOM_UTF8, BOM_UTF16, BOM_UTF16_BE, BOM_UTF16_LE
 
 # A dictionary mapping BOM to
 # the encoding to decode with, and what to set the
@@ -101,21 +87,6 @@ wspace_plus = ' \r\t\n\v\t\'"'
 tsquot = '"""%s"""'
 tdquot = "'''%s'''"
 
-try:
-    enumerate
-except NameError:
-    def enumerate(obj):
-        """enumerate for Python 2.2."""
-        i = -1
-        for item in obj:
-            i += 1
-            yield i, item
-
-try:
-    True, False
-except NameError:
-    True, False = 1, 0
-
 
 __version__ = '4.5.2'
 
@@ -814,7 +785,7 @@ class Section(dict):
         >>> c2
         {'section1': {'option1': 'False', 'subsection': {'more_options': 'False'}}}
         """
-        for key, val in indict.items():
+        for key, val in indict.iteritems():
             if (key in self and isinstance(self[key], dict) and
                                 isinstance(val, dict)):
                 self[key].merge(val)
@@ -1438,7 +1409,7 @@ class ConfigObj(Section):
             enc = BOM_LIST[self.encoding.lower()]
             if enc == 'utf_16':
                 # For UTF16 we try big endian and little endian
-                for BOM, (encoding, final_encoding) in BOMS.items():
+                for BOM, (encoding, final_encoding) in BOMS.iteritems():
                     if not final_encoding:
                         # skip UTF8
                         continue
@@ -1468,7 +1439,7 @@ class ConfigObj(Section):
             return self._decode(infile, self.encoding)
         
         # No encoding specified - so we need to check for UTF8/UTF16
-        for BOM, (encoding, final_encoding) in BOMS.items():
+        for BOM, (encoding, final_encoding) in BOMS.iteritems():
             if not line.startswith(BOM):
                 continue
             else:
@@ -2481,7 +2452,7 @@ def flatten_errors(cfg, res, levels=None, results=None):
         if levels:
             levels.pop()
         return results
-    for (key, val) in res.items():
+    for (key, val) in res.iteritems():
         if val == True:
             continue
         if isinstance(cfg.get(key), dict):
diff --git a/IPython/external/pretty.py b/IPython/external/pretty.py
index 6a7e855..2871252 100644
--- a/IPython/external/pretty.py
+++ b/IPython/external/pretty.py
@@ -138,9 +138,6 @@ def pprint(obj, verbose=False, max_width=79, newline='\n'):
     sys.stdout.write(newline)
     sys.stdout.flush()
 
-
-# add python2.5 context managers if we have the with statement feature
-if hasattr(__future__, 'with_statement'): exec '''
 from __future__ import with_statement
 from contextlib import contextmanager
 
@@ -164,16 +161,6 @@ class _PrettyPrinterBase(object):
                 yield
         finally:
             self.end_group(indent, close)
-'''
-else:
-    class _PrettyPrinterBase(object):
-
-        def _unsupported(self, *a, **kw):
-            """unsupported operation"""
-            raise RuntimeError('not available in this python version')
-        group = indent = _unsupported
-        del _unsupported
-
 
 class PrettyPrinter(_PrettyPrinterBase):
     """
diff --git a/IPython/external/pyparsing.py b/IPython/external/pyparsing.py
index 91b106a..aa60fd8 100644
--- a/IPython/external/pyparsing.py
+++ b/IPython/external/pyparsing.py
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
 # module pyparsing.py
 #
 # Copyright (c) 2003-2009  Paul T. McGuire
@@ -400,7 +401,7 @@ class ParseResults(object):
 
     def values( self ):
         """Returns all named result values."""
-        return [ v[-1][0] for v in self.__tokdict.values() ]
+        return [ v[-1][0] for v in self.__tokdict.itervalues() ]
 
     def __getattr__( self, name ):
         if name not in self.__slots__:
@@ -422,7 +423,7 @@ class ParseResults(object):
         if other.__tokdict:
             offset = len(self.__toklist)
             addoffset = ( lambda a: (a<0 and offset) or (a+offset) )
-            otheritems = other.__tokdict.items()
+            otheritems = other.__tokdict.iteritems()
             otherdictitems = [(k, _ParseResultsWithOffset(v[0],addoffset(v[1])) )
                                 for (k,vlist) in otheritems for v in vlist]
             for k,v in otherdictitems:
@@ -488,7 +489,7 @@ class ParseResults(object):
         """Returns the parse results as XML. Tags are created for tokens and lists that have defined results names."""
         nl = "\n"
         out = []
-        namedItems = dict( [ (v[1],k) for (k,vlist) in self.__tokdict.items()
+        namedItems = dict([(v[1],k) for (k,vlist) in self.__tokdict.iteritems()
                                                             for v in vlist ] )
         nextLevelIndent = indent + "  "
 
@@ -545,7 +546,7 @@ class ParseResults(object):
         return "".join(out)
 
     def __lookup(self,sub):
-        for k,vlist in self.__tokdict.items():
+        for k,vlist in self.__tokdict.iteritems():
             for v,loc in vlist:
                 if sub is v:
                     return k
@@ -2563,7 +2564,7 @@ class Each(ParseExpression):
                     tmp += ParseResults(r[k])
                     dups[k] = tmp
             finalResults += ParseResults(r)
-            for k,v in dups.items():
+            for k,v in dups.iteritems():
                 finalResults[k] = v
         return loc, finalResults
 
@@ -3442,7 +3443,7 @@ def withAttribute(*args,**attrDict):
     if args:
         attrs = args[:]
     else:
-        attrs = attrDict.items()
+        attrs = attrDict.iteritems()
     attrs = [(k,v) for k,v in attrs]
     def pa(s,l,tokens):
         for attrName,attrValue in attrs:
diff --git a/IPython/kernel/launcher.py b/IPython/kernel/launcher.py
index fbcc4e9..9b3f0e6 100644
--- a/IPython/kernel/launcher.py
+++ b/IPython/kernel/launcher.py
@@ -617,7 +617,7 @@ class WindowsHPCLauncher(BaseLauncher):
             # Twisted will raise DeprecationWarnings if we try to pass unicode to this
             output = yield getProcessOutput(str(self.job_cmd),
                 [str(a) for a in args],
-                env=dict((str(k),str(v)) for k,v in os.environ.items()),
+                env=dict((str(k),str(v)) for k,v in os.environ.iteritems()),
                 path=self.work_dir
             )
         except:
diff --git a/IPython/kernel/tests/test_pendingdeferred.py b/IPython/kernel/tests/test_pendingdeferred.py
index e12b56b..4ee8a58 100644
--- a/IPython/kernel/tests/test_pendingdeferred.py
+++ b/IPython/kernel/tests/test_pendingdeferred.py
@@ -59,7 +59,7 @@ class PendingDeferredManagerTest(DeferredTestCase):
             did = self.pdm.save_pending_deferred(d)
             dDict[did] = d
         # Make sure they are begin saved
-        for k in dDict.keys():
+        for k in dDict.iterkeys():
             self.assert_(self.pdm.quick_has_id(k))
         # Get the pending deferred (block=True), then callback with 'foo' and compare
         for did in dDict.keys()[0:5]:
diff --git a/IPython/kernel/winhpcjob.py b/IPython/kernel/winhpcjob.py
index b862bc8..c9219e2 100644
--- a/IPython/kernel/winhpcjob.py
+++ b/IPython/kernel/winhpcjob.py
@@ -212,7 +212,7 @@ class WinHPCTask(Configurable):
 
     def get_env_vars(self):
         env_vars = ET.Element('EnvironmentVariables')
-        for k, v in self.environment_variables.items():
+        for k, v in self.environment_variables.iteritems():
             variable = ET.SubElement(env_vars, "Variable")
             name = ET.SubElement(variable, "Name")
             name.text = k