summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorGuido van Rossum <guido@python.org>2007-02-11 06:12:03 +0000
committerGuido van Rossum <guido@python.org>2007-02-11 06:12:03 +0000
commitcc2b0161257495f859200bce0aea3ed7e646feb3 (patch)
treeba09aba0de6447bef5be59b43fb86d17d760833d
parent4e66dfcdc495218ad5f98b12ad6b4b2b05630ab0 (diff)
downloadcpython-git-cc2b0161257495f859200bce0aea3ed7e646feb3.tar.gz
- PEP 3106: dict.iterkeys(), .iteritems(), .itervalues() are now gone;
and .keys(), .items(), .values() return dict views. The dict views aren't fully functional yet; in particular, they can't be compared to sets yet. but they are useful as "iterator wells". There are still 27 failing unit tests; I expect that many of these have fairly trivial fixes, but there are so many, I could use help.
-rw-r--r--Include/abstract.h35
-rw-r--r--Lib/ConfigParser.py6
-rw-r--r--Lib/Cookie.py12
-rw-r--r--Lib/UserDict.py27
-rw-r--r--Lib/_LWPCookieJar.py3
-rw-r--r--Lib/_strptime.py2
-rw-r--r--Lib/_threading_local.py3
-rwxr-xr-xLib/base64.py4
-rw-r--r--Lib/compiler/ast.py2
-rw-r--r--Lib/compiler/misc.py2
-rw-r--r--Lib/compiler/pyassem.py4
-rw-r--r--Lib/cookielib.py3
-rw-r--r--Lib/copy.py6
-rw-r--r--Lib/csv.py6
-rw-r--r--Lib/ctypes/test/__init__.py2
-rw-r--r--Lib/difflib.py2
-rw-r--r--Lib/distutils/sysconfig.py2
-rw-r--r--Lib/dumbdbm.py4
-rw-r--r--Lib/encodings/punycode.py3
-rw-r--r--Lib/filecmp.py6
-rw-r--r--Lib/htmlentitydefs.py2
-rw-r--r--Lib/httplib.py4
-rwxr-xr-xLib/mailbox.py28
-rw-r--r--Lib/mailcap.py2
-rw-r--r--Lib/mhlib.py2
-rw-r--r--Lib/pickle.py2
-rwxr-xr-xLib/profile.py4
-rw-r--r--Lib/pstats.py29
-rw-r--r--Lib/pyclbr.py2
-rw-r--r--Lib/rfc822.py6
-rw-r--r--Lib/shelve.py2
-rwxr-xr-xLib/symbol.py2
-rw-r--r--Lib/symtable.py2
-rw-r--r--Lib/test/fork_wait.py3
-rw-r--r--Lib/test/mapping_tests.py18
-rw-r--r--Lib/test/pickletester.py4
-rw-r--r--Lib/test/string_tests.py2
-rw-r--r--Lib/test/test_anydbm.py6
-rwxr-xr-xLib/test/test_array.py2
-rwxr-xr-xLib/test/test_bsddb.py22
-rw-r--r--Lib/test/test_builtin.py16
-rw-r--r--Lib/test/test_cfgparser.py11
-rw-r--r--Lib/test/test_cgi.py4
-rw-r--r--Lib/test/test_compile.py4
-rw-r--r--Lib/test/test_cookie.py2
-rw-r--r--Lib/test/test_copy.py2
-rw-r--r--Lib/test/test_descr.py24
-rw-r--r--Lib/test/test_dictviews.py12
-rw-r--r--Lib/test/test_iter.py28
-rw-r--r--Lib/test/test_iterlen.py4
-rw-r--r--Lib/test/test_itertools.py4
-rw-r--r--Lib/test/test_mailbox.py16
-rw-r--r--Lib/test/test_mhlib.py4
-rw-r--r--Lib/test/test_richcmp.py4
-rw-r--r--Lib/test/test_site.py2
-rw-r--r--Lib/test/test_support.py5
-rw-r--r--Lib/test/test_urllib2.py5
-rw-r--r--Lib/test/test_userdict.py10
-rw-r--r--Lib/test/test_uuid.py2
-rw-r--r--Lib/test/test_weakref.py10
-rw-r--r--Lib/test/test_xmlrpc.py2
-rw-r--r--Lib/threading.py2
-rwxr-xr-xLib/token.py2
-rw-r--r--Lib/trace.py2
-rw-r--r--Lib/urllib2.py12
-rw-r--r--Lib/weakref.py20
-rw-r--r--Lib/xml/etree/ElementTree.py2
-rw-r--r--Misc/NEWS3
-rw-r--r--Modules/cPickle.c8
-rw-r--r--Modules/collectionsmodule.c13
-rw-r--r--Objects/abstract.c48
-rw-r--r--Objects/dictobject.c22
-rw-r--r--Objects/typeobject.c6
73 files changed, 317 insertions, 272 deletions
diff --git a/Include/abstract.h b/Include/abstract.h
index 1eab5f8a6b..661c28821c 100644
--- a/Include/abstract.h
+++ b/Include/abstract.h
@@ -1127,37 +1127,28 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
*/
- /* Implemented as macro:
+ PyAPI_FUNC(PyObject *) PyMapping_Keys(PyObject *o);
- PyObject *PyMapping_Keys(PyObject *o);
-
- On success, return a list of the keys in object o. On
- failure, return NULL. This is equivalent to the Python
- expression: o.keys().
+ /*
+ On success, return a list or tuple of the keys in object o.
+ On failure, return NULL.
*/
-#define PyMapping_Keys(O) PyObject_CallMethod(O,"keys",NULL)
-
- /* Implemented as macro:
- PyObject *PyMapping_Values(PyObject *o);
+ PyAPI_FUNC(PyObject *) PyMapping_Values(PyObject *o);
- On success, return a list of the values in object o. On
- failure, return NULL. This is equivalent to the Python
- expression: o.values().
+ /*
+ On success, return a list or tuple of the values in object o.
+ On failure, return NULL.
*/
-#define PyMapping_Values(O) PyObject_CallMethod(O,"values",NULL)
-
- /* Implemented as macro:
- PyObject *PyMapping_Items(PyObject *o);
+ PyAPI_FUNC(PyObject *) PyMapping_Items(PyObject *o);
- On success, return a list of the items in object o, where
- each item is a tuple containing a key-value pair. On
- failure, return NULL. This is equivalent to the Python
- expression: o.items().
+ /*
+ On success, return a list or tuple of the items in object o,
+ where each item is a tuple containing a key-value pair.
+ On failure, return NULL.
*/
-#define PyMapping_Items(O) PyObject_CallMethod(O,"items",NULL)
PyAPI_FUNC(PyObject *) PyMapping_GetItemString(PyObject *o, char *key);
diff --git a/Lib/ConfigParser.py b/Lib/ConfigParser.py
index bdc88cf25c..e080fcb43b 100644
--- a/Lib/ConfigParser.py
+++ b/Lib/ConfigParser.py
@@ -214,7 +214,7 @@ class RawConfigParser:
def sections(self):
"""Return a list of section names, excluding [DEFAULT]"""
# self._sections will never have [DEFAULT] in it
- return self._sections.keys()
+ return list(self._sections.keys())
def add_section(self, section):
"""Create a new section in the configuration.
@@ -242,7 +242,7 @@ class RawConfigParser:
opts.update(self._defaults)
if '__name__' in opts:
del opts['__name__']
- return opts.keys()
+ return list(opts.keys())
def read(self, filenames):
"""Read and parse a filename or a list of filenames.
@@ -547,7 +547,7 @@ class ConfigParser(RawConfigParser):
if vars:
for key, value in vars.items():
d[self.optionxform(key)] = value
- options = d.keys()
+ options = list(d.keys())
if "__name__" in options:
options.remove("__name__")
if raw:
diff --git a/Lib/Cookie.py b/Lib/Cookie.py
index fb06840de9..368a3bb5bd 100644
--- a/Lib/Cookie.py
+++ b/Lib/Cookie.py
@@ -488,8 +488,7 @@ class Morsel(dict):
# Now add any defined attributes
if attrs is None:
attrs = self._reserved
- items = self.items()
- items.sort()
+ items = sorted(self.items())
for K,V in items:
if V == "": continue
if K not in attrs: continue
@@ -582,8 +581,7 @@ class BaseCookie(dict):
def output(self, attrs=None, header="Set-Cookie:", sep="\015\012"):
"""Return a string suitable for HTTP."""
result = []
- items = self.items()
- items.sort()
+ items = sorted(self.items())
for K,V in items:
result.append( V.output(attrs, header) )
return sep.join(result)
@@ -593,8 +591,7 @@ class BaseCookie(dict):
def __repr__(self):
L = []
- items = self.items()
- items.sort()
+ items = sorted(self.items())
for K,V in items:
L.append( '%s=%s' % (K,repr(V.value) ) )
return '<%s: %s>' % (self.__class__.__name__, _spacejoin(L))
@@ -602,8 +599,7 @@ class BaseCookie(dict):
def js_output(self, attrs=None):
"""Return a string suitable for JavaScript."""
result = []
- items = self.items()
- items.sort()
+ items = sorted(self.items())
for K,V in items:
result.append( V.js_output(attrs) )
return _nulljoin(result)
diff --git a/Lib/UserDict.py b/Lib/UserDict.py
index 1190221b86..fa1deec988 100644
--- a/Lib/UserDict.py
+++ b/Lib/UserDict.py
@@ -42,9 +42,9 @@ class UserDict:
return c
def keys(self): return self.data.keys()
def items(self): return self.data.items()
- def iteritems(self): return self.data.iteritems()
- def iterkeys(self): return self.data.iterkeys()
- def itervalues(self): return self.data.itervalues()
+ def iteritems(self): return self.data.items()
+ def iterkeys(self): return self.data.keys()
+ def itervalues(self): return self.data.values()
def values(self): return self.data.values()
def update(self, dict=None, **kwargs):
if dict is None:
@@ -111,12 +111,12 @@ class DictMixin:
# fourth level uses definitions from lower levels
def itervalues(self):
- for _, v in self.iteritems():
+ for _, v in self.items():
yield v
def values(self):
- return [v for _, v in self.iteritems()]
+ return [v for _, v in self.items()]
def items(self):
- return list(self.iteritems())
+ return list(self.items())
def clear(self):
for key in self.keys():
del self[key]
@@ -140,7 +140,7 @@ class DictMixin:
return value
def popitem(self):
try:
- k, v = self.iteritems().next()
+ k, v = self.items().next()
except StopIteration:
raise KeyError, 'container is empty'
del self[k]
@@ -152,6 +152,9 @@ class DictMixin:
elif hasattr(other, 'iteritems'): # iteritems saves memory and lookups
for k, v in other.iteritems():
self[k] = v
+ elif hasattr(other, 'items'): # items may also save memory and lookups
+ for k, v in other.items():
+ self[k] = v
elif hasattr(other, 'keys'):
for k in other.keys():
self[k] = other[k]
@@ -166,14 +169,14 @@ class DictMixin:
except KeyError:
return default
def __repr__(self):
- return repr(dict(self.iteritems()))
+ return repr(dict(self.items()))
def __eq__(self, other):
if isinstance(other, DictMixin):
- other = dict(other.iteritems())
- return dict(self.iteritems()) == other
+ other = dict(other.items())
+ return dict(self.items()) == other
def __ne__(self, other):
if isinstance(other, DictMixin):
- other = dict(other.iteritems())
- return dict(self.iteritems()) != other
+ other = dict(other.items())
+ return dict(self.items()) != other
def __len__(self):
return len(self.keys())
diff --git a/Lib/_LWPCookieJar.py b/Lib/_LWPCookieJar.py
index 2a4fa7b2f6..67209583eb 100644
--- a/Lib/_LWPCookieJar.py
+++ b/Lib/_LWPCookieJar.py
@@ -37,8 +37,7 @@ def lwp_cookie_str(cookie):
if cookie.comment: h.append(("comment", cookie.comment))
if cookie.comment_url: h.append(("commenturl", cookie.comment_url))
- keys = cookie._rest.keys()
- keys.sort()
+ keys = sorted(cookie._rest.keys())
for k in keys:
h.append((k, str(cookie._rest[k])))
diff --git a/Lib/_strptime.py b/Lib/_strptime.py
index e389ce71f8..10b0083a7c 100644
--- a/Lib/_strptime.py
+++ b/Lib/_strptime.py
@@ -338,7 +338,7 @@ def strptime(data_string, format="%a %b %d %H:%M:%S %Y"):
# values
weekday = julian = -1
found_dict = found.groupdict()
- for group_key in found_dict.iterkeys():
+ for group_key in found_dict.keys():
# Directives not explicitly handled below:
# c, x, X
# handled by making out of other directives
diff --git a/Lib/_threading_local.py b/Lib/_threading_local.py
index f0ce857162..40a07f0688 100644
--- a/Lib/_threading_local.py
+++ b/Lib/_threading_local.py
@@ -28,8 +28,7 @@ local to a thread. If we access the data in a different thread:
>>> log = []
>>> def f():
- ... items = mydata.__dict__.items()
- ... items.sort()
+ ... items = sorted(mydata.__dict__.items())
... log.append(items)
... mydata.number = 11
... log.append(mydata.number)
diff --git a/Lib/base64.py b/Lib/base64.py
index 19de5143b0..4eb60f1a10 100755
--- a/Lib/base64.py
+++ b/Lib/base64.py
@@ -126,9 +126,7 @@ _b32alphabet = {
8: 'I', 17: 'R', 26: '2',
}
-_b32tab = _b32alphabet.items()
-_b32tab.sort()
-_b32tab = [v for k, v in _b32tab]
+_b32tab = [v for k, v in sorted(_b32alphabet.items())]
_b32rev = dict([(v, int(k)) for k, v in _b32alphabet.items()])
diff --git a/Lib/compiler/ast.py b/Lib/compiler/ast.py
index 259e1c45dd..bc283c08bd 100644
--- a/Lib/compiler/ast.py
+++ b/Lib/compiler/ast.py
@@ -1337,6 +1337,6 @@ class Yield(Node):
def __repr__(self):
return "Yield(%s)" % (repr(self.value),)
-for name, obj in globals().items():
+for name, obj in list(globals().items()):
if isinstance(obj, type) and issubclass(obj, Node):
nodes[name.lower()] = obj
diff --git a/Lib/compiler/misc.py b/Lib/compiler/misc.py
index 588c7fbd5a..b32d0dc00d 100644
--- a/Lib/compiler/misc.py
+++ b/Lib/compiler/misc.py
@@ -18,7 +18,7 @@ class Set:
def add(self, elt):
self.elts[elt] = elt
def elements(self):
- return self.elts.keys()
+ return list(self.elts.keys())
def has_elt(self, elt):
return elt in self.elts
def remove(self, elt):
diff --git a/Lib/compiler/pyassem.py b/Lib/compiler/pyassem.py
index 551791ed58..cac899d239 100644
--- a/Lib/compiler/pyassem.py
+++ b/Lib/compiler/pyassem.py
@@ -504,7 +504,7 @@ class PyFlowGraph(FlowGraph):
if name in cells]
for name in self.cellvars:
del cells[name]
- self.cellvars = self.cellvars + cells.keys()
+ self.cellvars = self.cellvars + list(cells.keys())
self.closure = self.cellvars + self.freevars
def _lookupName(self, name, list):
@@ -573,7 +573,7 @@ class PyFlowGraph(FlowGraph):
# similarly for other opcodes...
- for name, obj in locals().items():
+ for name, obj in list(locals().items()):
if name[:9] == "_convert_":
opname = name[9:]
_converters[opname] = obj
diff --git a/Lib/cookielib.py b/Lib/cookielib.py
index b27f63caf1..7fd883fd09 100644
--- a/Lib/cookielib.py
+++ b/Lib/cookielib.py
@@ -1171,8 +1171,7 @@ class DefaultCookiePolicy(CookiePolicy):
def vals_sorted_by_key(adict):
- keys = adict.keys()
- keys.sort()
+ keys = sorted(adict.keys())
return map(adict.get, keys)
def deepvalues(mapping):
diff --git a/Lib/copy.py b/Lib/copy.py
index 37e35cf93a..9bc794aefc 100644
--- a/Lib/copy.py
+++ b/Lib/copy.py
@@ -230,7 +230,7 @@ d[tuple] = _deepcopy_tuple
def _deepcopy_dict(x, memo):
y = {}
memo[id(x)] = y
- for key, value in x.iteritems():
+ for key, value in x.items():
y[deepcopy(key, memo)] = deepcopy(value, memo)
return y
d[dict] = _deepcopy_dict
@@ -302,7 +302,7 @@ def _reconstruct(x, info, deep, memo=None):
if state is not None:
y.__dict__.update(state)
if slotstate is not None:
- for key, value in slotstate.iteritems():
+ for key, value in slotstate.items():
setattr(y, key, value)
return y
@@ -337,7 +337,7 @@ def _test():
def __getstate__(self):
return {'a': self.a, 'arg': self.arg}
def __setstate__(self, state):
- for key, value in state.iteritems():
+ for key, value in state.items():
setattr(self, key, value)
def __deepcopy__(self, memo=None):
new = self.__class__(deepcopy(self.arg, memo))
diff --git a/Lib/csv.py b/Lib/csv.py
index e8c8cef815..92e4666032 100644
--- a/Lib/csv.py
+++ b/Lib/csv.py
@@ -278,7 +278,7 @@ class Sniffer:
charFrequency[char] = metaFrequency
for char in charFrequency.keys():
- items = charFrequency[char].items()
+ items = list(charFrequency[char].items())
if len(items) == 1 and items[0][0] == 0:
continue
# get the mode of the frequencies
@@ -308,7 +308,7 @@ class Sniffer:
consistency -= 0.01
if len(delims) == 1:
- delim = delims.keys()[0]
+ delim = list(delims.keys())[0]
skipinitialspace = (data[0].count(delim) ==
data[0].count("%c " % delim))
return (delim, skipinitialspace)
@@ -367,7 +367,7 @@ class Sniffer:
if len(row) != columns:
continue # skip rows that have irregular number of columns
- for col in columnTypes.keys():
+ for col in list(columnTypes.keys()):
for thisType in [int, int, float, complex]:
try:
diff --git a/Lib/ctypes/test/__init__.py b/Lib/ctypes/test/__init__.py
index 1101828cc9..5f7fcc2cae 100644
--- a/Lib/ctypes/test/__init__.py
+++ b/Lib/ctypes/test/__init__.py
@@ -41,7 +41,7 @@ def find_package_modules(package, mask):
hasattr(package.__loader__, '_files')):
path = package.__name__.replace(".", os.path.sep)
mask = os.path.join(path, mask)
- for fnm in package.__loader__._files.iterkeys():
+ for fnm in package.__loader__._files.keys():
if fnmatch.fnmatchcase(fnm, mask):
yield os.path.splitext(fnm)[0].replace(os.path.sep, ".")
else:
diff --git a/Lib/difflib.py b/Lib/difflib.py
index f2d13436b1..2dca7495d5 100644
--- a/Lib/difflib.py
+++ b/Lib/difflib.py
@@ -331,7 +331,7 @@ class SequenceMatcher:
junkdict = {}
if isjunk:
for d in populardict, b2j:
- for elt in d.keys():
+ for elt in list(d.keys()):
if isjunk(elt):
junkdict[elt] = 1
del d[elt]
diff --git a/Lib/distutils/sysconfig.py b/Lib/distutils/sysconfig.py
index 9de7234683..220b03310c 100644
--- a/Lib/distutils/sysconfig.py
+++ b/Lib/distutils/sysconfig.py
@@ -271,7 +271,7 @@ def parse_makefile(fn, g=None):
# do variable interpolation here
while notdone:
- for name in notdone.keys():
+ for name in list(notdone):
value = notdone[name]
m = _findvar1_rx.search(value) or _findvar2_rx.search(value)
if m:
diff --git a/Lib/dumbdbm.py b/Lib/dumbdbm.py
index 6c500bc4b9..1c9b57219a 100644
--- a/Lib/dumbdbm.py
+++ b/Lib/dumbdbm.py
@@ -109,7 +109,7 @@ class _Database(UserDict.DictMixin):
f = self._open(self._dirfile, 'w')
self._chmod(self._dirfile)
- for key, pos_and_siz_pair in self._index.iteritems():
+ for key, pos_and_siz_pair in self._index.items():
f.write("%r, %r\n" % (key, pos_and_siz_pair))
f.close()
@@ -202,7 +202,7 @@ class _Database(UserDict.DictMixin):
return key in self._index
def iterkeys(self):
- return self._index.iterkeys()
+ return self._index.keys()
__iter__ = iterkeys
def __len__(self):
diff --git a/Lib/encodings/punycode.py b/Lib/encodings/punycode.py
index d97200fd35..0e4aa0b9e2 100644
--- a/Lib/encodings/punycode.py
+++ b/Lib/encodings/punycode.py
@@ -17,8 +17,7 @@ def segregate(str):
base.append(c)
else:
extended[c] = 1
- extended = extended.keys()
- extended.sort()
+ extended = sorted(extended.keys())
return "".join(base).encode("ascii"),extended
def selective_len(str, max):
diff --git a/Lib/filecmp.py b/Lib/filecmp.py
index dda227256e..9c0ce5a851 100644
--- a/Lib/filecmp.py
+++ b/Lib/filecmp.py
@@ -187,7 +187,7 @@ class dircmp:
def phase4_closure(self): # Recursively call phase4() on subdirectories
self.phase4()
- for sd in self.subdirs.itervalues():
+ for sd in self.subdirs.values():
sd.phase4_closure()
def report(self): # Print a report on the differences between a and b
@@ -217,13 +217,13 @@ class dircmp:
def report_partial_closure(self): # Print reports on self and on subdirs
self.report()
- for sd in self.subdirs.itervalues():
+ for sd in self.subdirs.values():
print()
sd.report()
def report_full_closure(self): # Report on self and subdirs recursively
self.report()
- for sd in self.subdirs.itervalues():
+ for sd in self.subdirs.values():
print()
sd.report_full_closure()
diff --git a/Lib/htmlentitydefs.py b/Lib/htmlentitydefs.py
index 3dd14a79fa..bcc2420246 100644
--- a/Lib/htmlentitydefs.py
+++ b/Lib/htmlentitydefs.py
@@ -263,7 +263,7 @@ codepoint2name = {}
# (or a character reference if the character is outside the Latin-1 range)
entitydefs = {}
-for (name, codepoint) in name2codepoint.iteritems():
+for (name, codepoint) in name2codepoint.items():
codepoint2name[codepoint] = name
if codepoint <= 0xff:
entitydefs[name] = chr(codepoint)
diff --git a/Lib/httplib.py b/Lib/httplib.py
index 25075304ce..016144c39e 100644
--- a/Lib/httplib.py
+++ b/Lib/httplib.py
@@ -611,7 +611,7 @@ class HTTPResponse:
"""Return list of (header, value) tuples."""
if self.msg is None:
raise ResponseNotReady()
- return self.msg.items()
+ return list(self.msg.items())
class HTTPConnection:
@@ -902,7 +902,7 @@ class HTTPConnection:
if thelen is not None:
self.putheader('Content-Length',thelen)
- for hdr, value in headers.iteritems():
+ for hdr, value in headers.items():
self.putheader(hdr, value)
self.endheaders()
diff --git a/Lib/mailbox.py b/Lib/mailbox.py
index 3ef7e71ad9..d43f1dd674 100755
--- a/Lib/mailbox.py
+++ b/Lib/mailbox.py
@@ -95,11 +95,11 @@ class Mailbox:
def keys(self):
"""Return a list of keys."""
- return list(self.iterkeys())
+ return list(self.keys())
def itervalues(self):
"""Return an iterator over all messages."""
- for key in self.iterkeys():
+ for key in self.keys():
try:
value = self[key]
except KeyError:
@@ -107,15 +107,15 @@ class Mailbox:
yield value
def __iter__(self):
- return self.itervalues()
+ return self.values()
def values(self):
"""Return a list of messages. Memory intensive."""
- return list(self.itervalues())
+ return list(self.values())
def iteritems(self):
"""Return an iterator over (key, message) tuples."""
- for key in self.iterkeys():
+ for key in self.keys():
try:
value = self[key]
except KeyError:
@@ -124,7 +124,7 @@ class Mailbox:
def items(self):
"""Return a list of (key, message) tuples. Memory intensive."""
- return list(self.iteritems())
+ return list(self.items())
def __contains__(self, key):
"""Return True if the keyed message exists, False otherwise."""
@@ -136,7 +136,7 @@ class Mailbox:
def clear(self):
"""Delete all messages."""
- for key in self.iterkeys():
+ for key in self.keys():
self.discard(key)
def pop(self, key, default=None):
@@ -150,7 +150,7 @@ class Mailbox:
def popitem(self):
"""Delete an arbitrary (key, message) pair and return it."""
- for key in self.iterkeys():
+ for key in self.keys():
return (key, self.pop(key)) # This is only run once.
else:
raise KeyError('No messages in mailbox')
@@ -158,7 +158,7 @@ class Mailbox:
def update(self, arg=None):
"""Change the messages that correspond to certain keys."""
if hasattr(arg, 'iteritems'):
- source = arg.iteritems()
+ source = arg.items()
elif hasattr(arg, 'items'):
source = arg.items()
else:
@@ -477,7 +477,7 @@ class Maildir(Mailbox):
def next(self):
"""Return the next message in a one-time iteration."""
if not hasattr(self, '_onetime_keys'):
- self._onetime_keys = self.iterkeys()
+ self._onetime_keys = self.keys()
while True:
try:
return self[self._onetime_keys.next()]
@@ -950,7 +950,7 @@ class MH(Mailbox):
def __len__(self):
"""Return a count of messages in the mailbox."""
- return len(list(self.iterkeys()))
+ return len(list(self.keys()))
def lock(self):
"""Lock the mailbox."""
@@ -1038,7 +1038,7 @@ class MH(Mailbox):
f = open(os.path.join(self._path, '.mh_sequences'), 'r+')
try:
os.close(os.open(f.name, os.O_WRONLY | os.O_TRUNC))
- for name, keys in sequences.iteritems():
+ for name, keys in sequences.items():
if len(keys) == 0:
continue
f.write('%s:' % name)
@@ -1067,7 +1067,7 @@ class MH(Mailbox):
sequences = self.get_sequences()
prev = 0
changes = []
- for key in self.iterkeys():
+ for key in self.keys():
if key - 1 != prev:
changes.append((key, prev + 1))
if hasattr(os, 'link'):
@@ -1091,7 +1091,7 @@ class MH(Mailbox):
"""Inspect a new MHMessage and update sequences appropriately."""
pending_sequences = message.get_sequences()
all_sequences = self.get_sequences()
- for name, key_list in all_sequences.iteritems():
+ for name, key_list in all_sequences.items():
if name in pending_sequences:
key_list.append(key)
elif key in key_list:
diff --git a/Lib/mailcap.py b/Lib/mailcap.py
index fd17f5b265..086f05c581 100644
--- a/Lib/mailcap.py
+++ b/Lib/mailcap.py
@@ -24,7 +24,7 @@ def getcaps():
continue
morecaps = readmailcapfile(fp)
fp.close()
- for key, value in morecaps.iteritems():
+ for key, value in morecaps.items():
if not key in caps:
caps[key] = value
else:
diff --git a/Lib/mhlib.py b/Lib/mhlib.py
index bf9556c349..64aa6f74b2 100644
--- a/Lib/mhlib.py
+++ b/Lib/mhlib.py
@@ -314,7 +314,7 @@ class Folder:
"""Write the set of sequences back to the folder."""
fullname = self.getsequencesfilename()
f = None
- for key, seq in sequences.iteritems():
+ for key, seq in sequences.items():
s = IntSet('', ' ')
s.fromlist(seq)
if not f: f = open(fullname, 'w')
diff --git a/Lib/pickle.py b/Lib/pickle.py
index b828e1617a..db7f5124e5 100644
--- a/Lib/pickle.py
+++ b/Lib/pickle.py
@@ -666,7 +666,7 @@ class Pickler:
write(MARK + DICT)
self.memoize(obj)
- self._batch_setitems(obj.iteritems())
+ self._batch_setitems(iter(obj.items()))
dispatch[DictionaryType] = save_dict
if not PyStringMap is None:
diff --git a/Lib/profile.py b/Lib/profile.py
index 83480cf491..55118b5960 100755
--- a/Lib/profile.py
+++ b/Lib/profile.py
@@ -439,10 +439,10 @@ class Profile:
def snapshot_stats(self):
self.stats = {}
- for func, (cc, ns, tt, ct, callers) in self.timings.iteritems():
+ for func, (cc, ns, tt, ct, callers) in self.timings.items():
callers = callers.copy()
nc = 0
- for callcnt in callers.itervalues():
+ for callcnt in callers.values():
nc += callcnt
self.stats[func] = cc, nc, tt, ct, callers
diff --git a/Lib/pstats.py b/Lib/pstats.py
index 439ac84dd0..87038d9c21 100644
--- a/Lib/pstats.py
+++ b/Lib/pstats.py
@@ -163,7 +163,7 @@ class Stats:
self.fcn_list = None
- for func, stat in other.stats.iteritems():
+ for func, stat in other.stats.items():
if func in self.stats:
old_func_stat = self.stats[func]
else:
@@ -199,7 +199,7 @@ class Stats:
if not self.sort_arg_dict:
self.sort_arg_dict = dict = {}
bad_list = {}
- for word, tup in self.sort_arg_dict_default.iteritems():
+ for word, tup in self.sort_arg_dict_default.items():
fragment = word
while fragment:
if not fragment:
@@ -234,7 +234,7 @@ class Stats:
connector = ", "
stats_list = []
- for func, (cc, nc, tt, ct, callers) in self.stats.iteritems():
+ for func, (cc, nc, tt, ct, callers) in self.stats.items():
stats_list.append((cc, nc, tt, ct) + func +
(func_std_string(func), func))
@@ -254,12 +254,12 @@ class Stats:
oldstats = self.stats
self.stats = newstats = {}
max_name_len = 0
- for func, (cc, nc, tt, ct, callers) in oldstats.iteritems():
+ for func, (cc, nc, tt, ct, callers) in oldstats.items():
newfunc = func_strip_path(func)
if len(func_std_string(newfunc)) > max_name_len:
max_name_len = len(func_std_string(newfunc))
newcallers = {}
- for func2, caller in callers.iteritems():
+ for func2, caller in callers.items():
newcallers[func_strip_path(func2)] = caller
if newfunc in newstats:
@@ -282,10 +282,10 @@ class Stats:
def calc_callees(self):
if self.all_callees: return
self.all_callees = all_callees = {}
- for func, (cc, nc, tt, ct, callers) in self.stats.iteritems():
+ for func, (cc, nc, tt, ct, callers) in self.stats.items():
if not func in all_callees:
all_callees[func] = {}
- for func2, caller in callers.iteritems():
+ for func2, caller in callers.items():
if not func2 in all_callees:
all_callees[func2] = {}
all_callees[func2][func] = caller
@@ -394,9 +394,9 @@ class Stats:
print("Function ".ljust(name_size) + column_title, file=self.stream)
# print sub-header only if we have new-style callers
subheader = False
- for cc, nc, tt, ct, callers in self.stats.itervalues():
+ for cc, nc, tt, ct, callers in self.stats.values():
if callers:
- value = callers.itervalues().next()
+ value = iter(callers.values()).next()
subheader = isinstance(value, tuple)
break
if subheader:
@@ -407,8 +407,7 @@ class Stats:
if not call_dict:
print(file=self.stream)
return
- clist = call_dict.keys()
- clist.sort()
+ clist = sorted(call_dict.keys())
indent = ""
for func in clist:
name = func_std_string(func)
@@ -508,9 +507,9 @@ def add_func_stats(target, source):
def add_callers(target, source):
"""Combine two caller lists in a single list."""
new_callers = {}
- for func, caller in target.iteritems():
+ for func, caller in target.items():
new_callers[func] = caller
- for func, caller in source.iteritems():
+ for func, caller in source.items():
if func in new_callers:
new_callers[func] = caller + new_callers[func]
else:
@@ -520,7 +519,7 @@ def add_callers(target, source):
def count_calls(callers):
"""Sum the caller statistics to get total number of calls received."""
nc = 0
- for calls in callers.itervalues():
+ for calls in callers.values():
nc += calls
return nc
@@ -642,7 +641,7 @@ if __name__ == '__main__':
self.stats.sort_stats(*line.split())
else:
print("Valid sort keys (unique prefixes are accepted):", file=self.stream)
- for (key, value) in Stats.sort_arg_dict_default.iteritems():
+ for (key, value) in Stats.sort_arg_dict_default.items():
print("%s -- %s" % (key, value[1]), file=self.stream)
return 0
def help_sort(self):
diff --git a/Lib/pyclbr.py b/Lib/pyclbr.py
index a4ec3692f1..fdbfbd46cc 100644
--- a/Lib/pyclbr.py
+++ b/Lib/pyclbr.py
@@ -329,7 +329,7 @@ def _main():
for obj in objs:
if isinstance(obj, Class):
print("class", obj.name, obj.super, obj.lineno)
- methods = sorted(obj.methods.iteritems(), key=itemgetter(1))
+ methods = sorted(obj.methods.items(), key=itemgetter(1))
for name, lineno in methods:
if name != "__path__":
print(" def", name, lineno)
diff --git a/Lib/rfc822.py b/Lib/rfc822.py
index 8c636c1bd8..c4b7d373b0 100644
--- a/Lib/rfc822.py
+++ b/Lib/rfc822.py
@@ -437,18 +437,18 @@ class Message:
def keys(self):
"""Get all of a message's header field names."""
- return self.dict.keys()
+ return list(self.dict.keys())
def values(self):
"""Get all of a message's header field values."""
- return self.dict.values()
+ return list(self.dict.values())
def items(self):
"""Get all of a message's headers.
Returns a list of name, value tuples.
"""
- return self.dict.items()
+ return list(self.dict.items())
def __str__(self):
return ''.join(self.headers)
diff --git a/Lib/shelve.py b/Lib/shelve.py
index 2971354af0..d86718e141 100644
--- a/Lib/shelve.py
+++ b/Lib/shelve.py
@@ -144,7 +144,7 @@ class Shelf(UserDict.DictMixin):
def sync(self):
if self.writeback and self.cache:
self.writeback = False
- for key, entry in self.cache.iteritems():
+ for key, entry in self.cache.items():
self[key] = entry
self.writeback = True
self.cache = {}
diff --git a/Lib/symbol.py b/Lib/symbol.py
index d2cee12473..86aa2d052d 100755
--- a/Lib/symbol.py
+++ b/Lib/symbol.py
@@ -100,7 +100,7 @@ yield_expr = 342
#--end constants--
sym_name = {}
-for _name, _value in globals().items():
+for _name, _value in list(globals().items()):
if type(_value) is type(0):
sym_name[_value] = _name
diff --git a/Lib/symtable.py b/Lib/symtable.py
index d18d30b816..e3c5b52ced 100644
--- a/Lib/symtable.py
+++ b/Lib/symtable.py
@@ -13,7 +13,7 @@ __all__ = ["symtable", "SymbolTable", "newSymbolTable", "Class",
def symtable(code, filename, compile_type):
raw = _symtable.symtable(code, filename, compile_type)
- for top in raw.itervalues():
+ for top in raw.values():
if top.name == 'top':
break
return newSymbolTable(top, filename)
diff --git a/Lib/test/fork_wait.py b/Lib/test/fork_wait.py
index 7eb55f6683..9c4df4b14d 100644
--- a/Lib/test/fork_wait.py
+++ b/Lib/test/fork_wait.py
@@ -51,8 +51,7 @@ class ForkWait(unittest.TestCase):
time.sleep(LONGSLEEP)
- a = self.alive.keys()
- a.sort()
+ a = sorted(self.alive.keys())
self.assertEquals(a, range(NUM_THREADS))
prefork_lives = self.alive.copy()
diff --git a/Lib/test/mapping_tests.py b/Lib/test/mapping_tests.py
index 6b872c4a74..25fec4e795 100644
--- a/Lib/test/mapping_tests.py
+++ b/Lib/test/mapping_tests.py
@@ -73,13 +73,13 @@ class BasicTestMappingProtocol(unittest.TestCase):
self.assert_(hasattr(iter, '__iter__'))
x = list(iter)
self.assert_(set(x)==set(lst)==set(ref))
- check_iterandlist(d.iterkeys(), d.keys(), self.reference.keys())
+ check_iterandlist(d.keys(), d.keys(), self.reference.keys())
check_iterandlist(iter(d), d.keys(), self.reference.keys())
- check_iterandlist(d.itervalues(), d.values(), self.reference.values())
- check_iterandlist(d.iteritems(), d.items(), self.reference.items())
+ check_iterandlist(d.values(), d.values(), self.reference.values())
+ check_iterandlist(d.items(), d.items(), self.reference.items())
#get
- key, value = d.iteritems().next()
- knownkey, knownvalue = self.other.iteritems().next()
+ key, value = d.items().next()
+ knownkey, knownvalue = self.other.items().next()
self.assertEqual(d.get(key, knownvalue), value)
self.assertEqual(d.get(knownkey, knownvalue), knownvalue)
self.failIf(knownkey in d)
@@ -104,8 +104,8 @@ class BasicTestMappingProtocol(unittest.TestCase):
self.assertEqual(dict(p), self.reference)
d = self._full_mapping(self.reference)
#setdefault
- key, value = d.iteritems().next()
- knownkey, knownvalue = self.other.iteritems().next()
+ key, value = d.items().next()
+ knownkey, knownvalue = self.other.items().next()
self.assertEqual(d.setdefault(key, knownvalue), value)
self.assertEqual(d[key], value)
self.assertEqual(d.setdefault(knownkey, knownvalue), knownvalue)
@@ -183,7 +183,7 @@ class BasicTestMappingProtocol(unittest.TestCase):
# Iterator
d = self._empty_mapping()
- d.update(self.other.iteritems())
+ d.update(self.other.items())
self.assertEqual(d.items(), self.other.items())
# FIXME: Doesn't work with UserDict
@@ -400,7 +400,7 @@ class TestMappingProtocol(BasicTestMappingProtocol):
# iterator
d = self._full_mapping({1:3, 2:4})
- d.update(self._full_mapping({1:2, 3:4, 5:6}).iteritems())
+ d.update(self._full_mapping({1:2, 3:4, 5:6}).items())
self.assertEqual(d, {1:2, 2:4, 3:4, 5:6})
class SimpleUserDict:
diff --git a/Lib/test/pickletester.py b/Lib/test/pickletester.py
index 5d340b3616..cb4b4319b6 100644
--- a/Lib/test/pickletester.py
+++ b/Lib/test/pickletester.py
@@ -438,7 +438,7 @@ class AbstractPickleTests(unittest.TestCase):
for proto in protocols:
s = self.dumps(d, proto)
x = self.loads(s)
- self.assertEqual(x.keys(), [1])
+ self.assertEqual(list(x.keys()), [1])
self.assert_(x[1] is x)
def test_recursive_inst(self):
@@ -461,7 +461,7 @@ class AbstractPickleTests(unittest.TestCase):
x = self.loads(s)
self.assertEqual(len(x), 1)
self.assertEqual(dir(x[0]), dir(i))
- self.assertEqual(x[0].attr.keys(), [1])
+ self.assertEqual(list(x[0].attr.keys()), [1])
self.assert_(x[0].attr[1] is x)
def test_garyp(self):
diff --git a/Lib/test/string_tests.py b/Lib/test/string_tests.py
index 17e338952e..e6b419f7c5 100644
--- a/Lib/test/string_tests.py
+++ b/Lib/test/string_tests.py
@@ -40,7 +40,7 @@ class CommonTest(unittest.TestCase):
elif isinstance(obj, dict):
return dict([
(self.fixtype(key), self.fixtype(value))
- for (key, value) in obj.iteritems()
+ for (key, value) in obj.items()
])
else:
return obj
diff --git a/Lib/test/test_anydbm.py b/Lib/test/test_anydbm.py
index 0cdc2c321d..46d46d961a 100644
--- a/Lib/test/test_anydbm.py
+++ b/Lib/test/test_anydbm.py
@@ -72,10 +72,8 @@ class AnyDBMTestCase(unittest.TestCase):
f.close()
def keys_helper(self, f):
- keys = f.keys()
- keys.sort()
- dkeys = self._dict.keys()
- dkeys.sort()
+ keys = sorted(f.keys())
+ dkeys = sorted(self._dict.keys())
self.assertEqual(keys, dkeys)
return keys
diff --git a/Lib/test/test_array.py b/Lib/test/test_array.py
index 6abfb90d73..692760ce90 100755
--- a/Lib/test/test_array.py
+++ b/Lib/test/test_array.py
@@ -729,7 +729,7 @@ class CharacterTest(StringTest):
self.assertEqual(s.color, "blue")
s.color = "red"
self.assertEqual(s.color, "red")
- self.assertEqual(s.__dict__.keys(), ["color"])
+ self.assertEqual(list(s.__dict__.keys()), ["color"])
def test_nounicode(self):
a = array.array(self.typecode, self.example)
diff --git a/Lib/test/test_bsddb.py b/Lib/test/test_bsddb.py
index 3b33c48b9c..d7f11775fa 100755
--- a/Lib/test/test_bsddb.py
+++ b/Lib/test/test_bsddb.py
@@ -15,7 +15,7 @@ class TestBSDDB(unittest.TestCase):
def setUp(self):
self.f = self.openmethod[0](self.fname, self.openflag, cachesize=32768)
self.d = dict(q='Guido', w='van', e='Rossum', r='invented', t='Python', y='')
- for k, v in self.d.iteritems():
+ for k, v in self.d.items():
self.f[k] = v
def tearDown(self):
@@ -29,7 +29,7 @@ class TestBSDDB(unittest.TestCase):
pass
def test_getitem(self):
- for k, v in self.d.iteritems():
+ for k, v in self.d.items():
self.assertEqual(self.f[k], v)
def test_len(self):
@@ -48,7 +48,7 @@ class TestBSDDB(unittest.TestCase):
return
self.f.close()
self.f = self.openmethod[0](self.fname, 'w')
- for k, v in self.d.iteritems():
+ for k, v in self.d.items():
self.assertEqual(self.f[k], v)
def assertSetEquals(self, seqn1, seqn2):
@@ -61,9 +61,9 @@ class TestBSDDB(unittest.TestCase):
self.assertSetEquals(d.keys(), f.keys())
self.assertSetEquals(d.values(), f.values())
self.assertSetEquals(d.items(), f.items())
- self.assertSetEquals(d.iterkeys(), f.iterkeys())
- self.assertSetEquals(d.itervalues(), f.itervalues())
- self.assertSetEquals(d.iteritems(), f.iteritems())
+ self.assertSetEquals(d.keys(), f.keys())
+ self.assertSetEquals(d.values(), f.values())
+ self.assertSetEquals(d.items(), f.items())
def test_iter_while_modifying_values(self):
if not hasattr(self.f, '__iter__'):
@@ -94,7 +94,7 @@ class TestBSDDB(unittest.TestCase):
if not hasattr(self.f, 'iteritems'):
return
- di = self.d.iteritems()
+ di = self.d.items()
while 1:
try:
k, v = di.next()
@@ -105,7 +105,7 @@ class TestBSDDB(unittest.TestCase):
# it should behave the same as a dict. modifying values
# of existing keys should not break iteration. (adding
# or removing keys should)
- fi = self.f.iteritems()
+ fi = self.f.items()
while 1:
try:
k, v = fi.next()
@@ -159,7 +159,7 @@ class TestBSDDB(unittest.TestCase):
# test the iterator interface (if present)
if hasattr(self.f, 'iteritems'):
if debug: print("D")
- i = self.f.iteritems()
+ i = self.f.items()
k,v = i.next()
if debug: print("E")
self.f[k] = "please don't deadlock"
@@ -198,7 +198,7 @@ class TestBSDDB(unittest.TestCase):
# do the bsddb._DBWithCursor _iter_mixin internals leak cursors?
nc1 = len(self.f._cursor_refs)
# create iterator
- i = self.f.iteritems()
+ i = self.f.items()
nc2 = len(self.f._cursor_refs)
# use the iterator (should run to the first yeild, creating the cursor)
k, v = i.next()
@@ -240,7 +240,7 @@ class TestBSDDB(unittest.TestCase):
new = dict(y='life', u='of', i='brian')
self.f.update(new)
self.d.update(new)
- for k, v in self.d.iteritems():
+ for k, v in self.d.items():
self.assertEqual(self.f[k], v)
def test_keyordering(self):
diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py
index ab9dfc8cf0..b6ac990b5c 100644
--- a/Lib/test/test_builtin.py
+++ b/Lib/test/test_builtin.py
@@ -290,8 +290,8 @@ class BuiltinTest(unittest.TestCase):
if key == 'a':
return 12
raise KeyError
- def keys(self):
- return list('xyz')
+ def __iter__(self):
+ return iter('xyz')
m = M()
g = globals()
@@ -313,8 +313,8 @@ class BuiltinTest(unittest.TestCase):
if key == 'a':
return 12
return dict.__getitem__(self, key)
- def keys(self):
- return list('xyz')
+ def __iter__(self):
+ return iter('xyz')
d = D()
self.assertEqual(eval('a', g, d), 12)
@@ -346,8 +346,8 @@ class BuiltinTest(unittest.TestCase):
class C:
def __getitem__(self, item):
raise KeyError(item)
- def keys(self):
- return 'a'
+ def __iter__(self):
+ return 'a' # XXX Not quite faithful to the SF bug...
self.assertRaises(TypeError, eval, 'dir()', globals(), C())
# Done outside of the method test_z to get the correct scope
@@ -522,8 +522,8 @@ class BuiltinTest(unittest.TestCase):
unicode("123"): unicode("112233")
}
- for (cls, inps) in inputs.iteritems():
- for (inp, exp) in inps.iteritems():
+ for (cls, inps) in inputs.items():
+ for (inp, exp) in inps.items():
# make sure the output goes through __getitem__
# even if func is None
self.assertEqual(
diff --git a/Lib/test/test_cfgparser.py b/Lib/test/test_cfgparser.py
index 8aa1df3f2a..229577270d 100644
--- a/Lib/test/test_cfgparser.py
+++ b/Lib/test/test_cfgparser.py
@@ -7,18 +7,13 @@ from test import test_support
class SortedDict(UserDict.UserDict):
def items(self):
- result = self.data.items()
- result.sort()
- return result
+ return sorted(self.data.items())
def keys(self):
- result = self.data.keys()
- result.sort()
- return result
+ return sorted(self.data.keys())
def values(self):
- result = self.items()
- return [i[1] for i in values]
+ return [i[1] for i in self.items()]
def iteritems(self): return iter(self.items())
def iterkeys(self): return iter(self.keys())
diff --git a/Lib/test/test_cgi.py b/Lib/test/test_cgi.py
index 9cf6a121ac..260d9b2a85 100644
--- a/Lib/test/test_cgi.py
+++ b/Lib/test/test_cgi.py
@@ -118,9 +118,7 @@ parse_strict_test_cases = [
]
def norm(seq):
- if isinstance(seq, list):
- seq.sort(key=repr)
- return seq
+ return sorted(seq, key=repr)
def first_elts(list):
return map(lambda x:x[0], list)
diff --git a/Lib/test/test_compile.py b/Lib/test/test_compile.py
index 1acb4a1f5d..2b5a135ab2 100644
--- a/Lib/test/test_compile.py
+++ b/Lib/test/test_compile.py
@@ -53,8 +53,8 @@ class TestSpecifics(unittest.TestCase):
raise KeyError
def __setitem__(self, key, value):
self.results = (key, value)
- def keys(self):
- return list('xyz')
+ def __iter__(self):
+ return iter('xyz')
m = M()
g = globals()
diff --git a/Lib/test/test_cookie.py b/Lib/test/test_cookie.py
index e7c0cf1ccc..e4c8975818 100644
--- a/Lib/test/test_cookie.py
+++ b/Lib/test/test_cookie.py
@@ -38,7 +38,7 @@ class CookieTests(unittest.TestCase):
C.load(case['data'])
self.assertEqual(repr(C), case['repr'])
self.assertEqual(C.output(sep='\n'), case['output'])
- for k, v in sorted(case['dict'].iteritems()):
+ for k, v in sorted(case['dict'].items()):
self.assertEqual(C[k].value, v)
def test_load(self):
diff --git a/Lib/test/test_copy.py b/Lib/test/test_copy.py
index 8a32866b39..cb075c3b4b 100644
--- a/Lib/test/test_copy.py
+++ b/Lib/test/test_copy.py
@@ -491,7 +491,7 @@ class TestCopy(unittest.TestCase):
def test_reduce_5tuple(self):
class C(dict):
def __reduce__(self):
- return (C, (), self.__dict__, None, self.iteritems())
+ return (C, (), self.__dict__, None, self.items())
def __eq__(self, other):
return (dict(self) == dict(other) and
self.__dict__ == other.__dict__)
diff --git a/Lib/test/test_descr.py b/Lib/test/test_descr.py
index aab33314a4..d369cf6305 100644
--- a/Lib/test/test_descr.py
+++ b/Lib/test/test_descr.py
@@ -183,7 +183,7 @@ def dict_constructor():
d = dict({1: 2, 'a': 'b'})
vereq(d, {1: 2, 'a': 'b'})
vereq(d, dict(d.items()))
- vereq(d, dict(d.iteritems()))
+ vereq(d, dict(d.items()))
d = dict({'one':1, 'two':2})
vereq(d, dict(one=1, two=2))
vereq(d, dict(**d))
@@ -541,10 +541,10 @@ def spamdicts():
class C(spam.spamdict):
def foo(self): return 1
a = C()
- vereq(a.items(), [])
+ vereq(list(a.items()), [])
vereq(a.foo(), 1)
a['foo'] = 'bar'
- vereq(a.items(), [('foo', 'bar')])
+ vereq(list(a.items()), [('foo', 'bar')])
vereq(a.getstate(), 0)
a.setstate(100)
vereq(a.getstate(), 100)
@@ -714,7 +714,7 @@ def metaclass():
# named _get_x and/or _set_x are found
def __new__(metaclass, name, bases, dict):
hits = {}
- for key, val in dict.iteritems():
+ for key, val in dict.items():
if key.startswith("_get_"):
key = key[5:]
get, set = hits.get(key, (None, None))
@@ -725,7 +725,7 @@ def metaclass():
get, set = hits.get(key, (None, None))
set = val
hits[key] = get, set
- for key, (get, set) in hits.iteritems():
+ for key, (get, set) in hits.items():
dict[key] = property(get, set)
return super(autoproperty, metaclass).__new__(metaclass,
name, bases, dict)
@@ -820,9 +820,9 @@ def multi():
type({}).__init__(self)
C.__init__(self)
d = D()
- vereq(d.keys(), [])
+ vereq(list(d.keys()), [])
d["hello"] = "world"
- vereq(d.items(), [("hello", "world")])
+ vereq(list(d.items()), [("hello", "world")])
vereq(d["hello"], "world")
vereq(d.getstate(), 0)
d.setstate(10)
@@ -2676,9 +2676,7 @@ def pickles():
cPickle = None
def sorteditems(d):
- L = d.items()
- L.sort()
- return L
+ return sorted(d.items())
global C
class C(object):
@@ -3193,7 +3191,7 @@ def dictproxyiterkeys():
def meth(self):
pass
if verbose: print("Testing dict-proxy iterkeys...")
- keys = [ key for key in C.__dict__.iterkeys() ]
+ keys = [ key for key in C.__dict__.keys() ]
keys.sort()
vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
@@ -3202,7 +3200,7 @@ def dictproxyitervalues():
def meth(self):
pass
if verbose: print("Testing dict-proxy itervalues...")
- values = [ values for values in C.__dict__.itervalues() ]
+ values = [ values for values in C.__dict__.values() ]
vereq(len(values), 5)
def dictproxyiteritems():
@@ -3210,7 +3208,7 @@ def dictproxyiteritems():
def meth(self):
pass
if verbose: print("Testing dict-proxy iteritems...")
- keys = [ key for (key, value) in C.__dict__.iteritems() ]
+ keys = [ key for (key, value) in C.__dict__.items() ]
keys.sort()
vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
diff --git a/Lib/test/test_dictviews.py b/Lib/test/test_dictviews.py
index 4c436f7eae..607d182011 100644
--- a/Lib/test/test_dictviews.py
+++ b/Lib/test/test_dictviews.py
@@ -4,19 +4,19 @@ from test import test_support
class DictSetTest(unittest.TestCase):
def test_constructors_not_callable(self):
- kt = type({}.KEYS())
+ kt = type({}.keys())
self.assertRaises(TypeError, kt, {})
self.assertRaises(TypeError, kt)
- it = type({}.ITEMS())
+ it = type({}.items())
self.assertRaises(TypeError, it, {})
self.assertRaises(TypeError, it)
- vt = type({}.VALUES())
+ vt = type({}.values())
self.assertRaises(TypeError, vt, {})
self.assertRaises(TypeError, vt)
def test_dict_keys(self):
d = {1: 10, "a": "ABC"}
- keys = d.KEYS()
+ keys = d.keys()
self.assertEqual(set(keys), {1, "a"})
self.assertEqual(len(keys), 2)
self.assert_(1 in keys)
@@ -26,7 +26,7 @@ class DictSetTest(unittest.TestCase):
def test_dict_items(self):
d = {1: 10, "a": "ABC"}
- items = d.ITEMS()
+ items = d.items()
self.assertEqual(set(items), {(1, 10), ("a", "ABC")})
self.assertEqual(len(items), 2)
self.assert_((1, 10) in items)
@@ -39,7 +39,7 @@ class DictSetTest(unittest.TestCase):
def test_dict_values(self):
d = {1: 10, "a": "ABC"}
- values = d.VALUES()
+ values = d.values()
self.assertEqual(set(values), {10, "ABC"})
self.assertEqual(len(values), 2)
diff --git a/Lib/test/test_iter.py b/Lib/test/test_iter.py
index 76af429de1..24a4f77799 100644
--- a/Lib/test/test_iter.py
+++ b/Lib/test/test_iter.py
@@ -365,8 +365,8 @@ class TestCase(unittest.TestCase):
d = {"one": 1, "two": 2, "three": 3}
self.assertEqual(max(d), "two")
self.assertEqual(min(d), "one")
- self.assertEqual(max(d.itervalues()), 3)
- self.assertEqual(min(iter(d.itervalues())), 1)
+ self.assertEqual(max(d.values()), 3)
+ self.assertEqual(min(iter(d.values())), 1)
f = open(TESTFN, "w")
try:
@@ -402,7 +402,7 @@ class TestCase(unittest.TestCase):
for i in range(5)]
self.assertEqual(map(None, d,
SequenceClass(5),
- iter(d.iterkeys())),
+ iter(d.keys())),
expected)
f = open(TESTFN, "w")
@@ -437,7 +437,7 @@ class TestCase(unittest.TestCase):
[(0,), (1,), (2,)])
d = {"one": 1, "two": 2, "three": 3}
- self.assertEqual(d.items(), list(zip(d, d.itervalues())))
+ self.assertEqual(d.items(), list(zip(d, d.values())))
# Generate all ints starting at constructor arg.
class IntsFrom:
@@ -559,13 +559,13 @@ class TestCase(unittest.TestCase):
d = {"one": 1, "two": 2, "three": 3, 1j: 2j}
for k in d:
self.assert_(k in d)
- self.assert_(k not in d.itervalues())
+ self.assert_(k not in d.values())
for v in d.values():
- self.assert_(v in d.itervalues())
+ self.assert_(v in d.values())
self.assert_(v not in d)
- for k, v in d.iteritems():
- self.assert_((k, v) in d.iteritems())
- self.assert_((v, k) not in d.iteritems())
+ for k, v in d.items():
+ self.assert_((k, v) in d.items())
+ self.assert_((v, k) not in d.items())
f = open(TESTFN, "w")
try:
@@ -600,9 +600,9 @@ class TestCase(unittest.TestCase):
d = {"one": 3, "two": 3, "three": 3, 1j: 2j}
for k in d:
self.assertEqual(countOf(d, k), 1)
- self.assertEqual(countOf(d.itervalues(), 3), 3)
- self.assertEqual(countOf(d.itervalues(), 2j), 1)
- self.assertEqual(countOf(d.itervalues(), 1j), 0)
+ self.assertEqual(countOf(d.values(), 3), 3)
+ self.assertEqual(countOf(d.values(), 2j), 1)
+ self.assertEqual(countOf(d.values(), 1j), 0)
f = open(TESTFN, "w")
try:
@@ -744,7 +744,7 @@ class TestCase(unittest.TestCase):
else:
self.fail("should have raised TypeError")
- a, b, c = {1: 42, 2: 42, 3: 42}.itervalues()
+ a, b, c = {1: 42, 2: 42, 3: 42}.values()
self.assertEqual((a, b, c), (42, 42, 42))
f = open(TESTFN, "w")
@@ -841,7 +841,7 @@ class TestCase(unittest.TestCase):
# XXX For a more thorough test, see towards the end of:
# http://mail.python.org/pipermail/python-dev/2002-July/026512.html
a = {1:1, 2:2, 0:0, 4:4, 3:3}
- for b in iter(a), a.iterkeys(), a.iteritems(), a.itervalues():
+ for b in iter(a), a.keys(), a.items(), a.values():
b = iter(a)
self.assertEqual(len(list(b)), 5)
self.assertEqual(list(b), [])
diff --git a/Lib/test/test_iterlen.py b/Lib/test/test_iterlen.py
index af4467e137..e9a6a68816 100644
--- a/Lib/test/test_iterlen.py
+++ b/Lib/test/test_iterlen.py
@@ -139,14 +139,14 @@ class TestDictItems(TestTemporarilyImmutable):
def setUp(self):
d = dict.fromkeys(xrange(n))
- self.it = d.iteritems()
+ self.it = d.items()
self.mutate = d.popitem
class TestDictValues(TestTemporarilyImmutable):
def setUp(self):
d = dict.fromkeys(xrange(n))
- self.it = d.itervalues()
+ self.it = d.values()
self.mutate = d.popitem
class TestSet(TestTemporarilyImmutable):
diff --git a/Lib/test/test_itertools.py b/Lib/test/test_itertools.py
index a083e7ce8e..ac30495568 100644
--- a/Lib/test/test_itertools.py
+++ b/Lib/test/test_itertools.py
@@ -790,7 +790,7 @@ Samuele
>>> from operator import itemgetter
>>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3)
->>> di = sorted(sorted(d.iteritems()), key=itemgetter(1))
+>>> di = sorted(sorted(d.items()), key=itemgetter(1))
>>> for k, g in groupby(di, itemgetter(1)):
... print(k, map(itemgetter(0), g))
...
@@ -823,7 +823,7 @@ Samuele
... return imap(function, count())
>>> def iteritems(mapping):
-... return izip(mapping.iterkeys(), mapping.itervalues())
+... return izip(mapping.keys(), mapping.values())
>>> def nth(iterable, n):
... "Returns the nth item"
diff --git a/Lib/test/test_mailbox.py b/Lib/test/test_mailbox.py
index eb675f645c..181e32b555 100644
--- a/Lib/test/test_mailbox.py
+++ b/Lib/test/test_mailbox.py
@@ -24,7 +24,7 @@ class TestBase(unittest.TestCase):
# Inspect a mailbox.Message representation of the sample message
self.assert_(isinstance(msg, email.message.Message))
self.assert_(isinstance(msg, mailbox.Message))
- for key, value in _sample_headers.iteritems():
+ for key, value in _sample_headers.items():
self.assert_(value in msg.get_all(key))
self.assert_(msg.is_multipart())
self.assert_(len(msg.get_payload()) == len(_sample_payloads))
@@ -174,7 +174,7 @@ class TestMailbox(TestBase):
def test_iterkeys(self):
# Get keys using iterkeys()
- self._check_iteration(self._box.iterkeys, do_keys=True, do_values=False)
+ self._check_iteration(self._box.keys, do_keys=True, do_values=False)
def test_keys(self):
# Get keys using keys()
@@ -182,7 +182,7 @@ class TestMailbox(TestBase):
def test_itervalues(self):
# Get values using itervalues()
- self._check_iteration(self._box.itervalues, do_keys=False,
+ self._check_iteration(self._box.values, do_keys=False,
do_values=True)
def test_iter(self):
@@ -196,7 +196,7 @@ class TestMailbox(TestBase):
def test_iteritems(self):
# Get keys and values using iteritems()
- self._check_iteration(self._box.iteritems, do_keys=True,
+ self._check_iteration(self._box.items, do_keys=True,
do_values=True)
def test_items(self):
@@ -424,12 +424,12 @@ class TestMailboxSuperclass(TestBase):
self.assertRaises(NotImplementedError, lambda: box.__delitem__(''))
self.assertRaises(NotImplementedError, lambda: box.discard(''))
self.assertRaises(NotImplementedError, lambda: box.__setitem__('', ''))
- self.assertRaises(NotImplementedError, lambda: box.iterkeys())
self.assertRaises(NotImplementedError, lambda: box.keys())
- self.assertRaises(NotImplementedError, lambda: box.itervalues().next())
+ self.assertRaises(NotImplementedError, lambda: box.keys())
+ self.assertRaises(NotImplementedError, lambda: box.values().next())
self.assertRaises(NotImplementedError, lambda: box.__iter__().next())
self.assertRaises(NotImplementedError, lambda: box.values())
- self.assertRaises(NotImplementedError, lambda: box.iteritems().next())
+ self.assertRaises(NotImplementedError, lambda: box.items().next())
self.assertRaises(NotImplementedError, lambda: box.items())
self.assertRaises(NotImplementedError, lambda: box.get(''))
self.assertRaises(NotImplementedError, lambda: box.__getitem__(''))
@@ -709,7 +709,7 @@ class _TestMboxMMDF(TestMailbox):
mtime = os.path.getmtime(self._path)
self._box = self._factory(self._path)
self.assert_(len(self._box) == 3)
- for key in self._box.iterkeys():
+ for key in self._box.keys():
self.assert_(self._box.get_string(key) in values)
self._box.close()
self.assert_(mtime == os.path.getmtime(self._path))
diff --git a/Lib/test/test_mhlib.py b/Lib/test/test_mhlib.py
index a6dc00ad92..5c8b40dce6 100644
--- a/Lib/test/test_mhlib.py
+++ b/Lib/test/test_mhlib.py
@@ -46,7 +46,7 @@ def readFile(fname):
return r
def writeProfile(dict):
- contents = [ "%s: %s\n" % (k, v) for k, v in dict.iteritems() ]
+ contents = [ "%s: %s\n" % (k, v) for k, v in dict.items() ]
writeFile(_mhprofile, "".join(contents))
def writeContext(folder):
@@ -61,7 +61,7 @@ def writeCurMessage(folder, cur):
def writeMessage(folder, n, headers, body):
folder = normF(folder)
- headers = "".join([ "%s: %s\n" % (k, v) for k, v in headers.iteritems() ])
+ headers = "".join([ "%s: %s\n" % (k, v) for k, v in headers.items() ])
contents = "%s\n%s\n" % (headers,body)
mkdirs(os.path.join(_mhpath, folder))
writeFile(os.path.join(_mhpath, folder, str(n)), contents)
diff --git a/Lib/test/test_richcmp.py b/Lib/test/test_richcmp.py
index 9c4a7a05e6..72a6de891a 100644
--- a/Lib/test/test_richcmp.py
+++ b/Lib/test/test_richcmp.py
@@ -131,7 +131,7 @@ class VectorTest(unittest.TestCase):
self.checkequal("gt", a, b, [False, False, False, True, True ])
self.checkequal("ge", a, b, [False, False, True, True, True ])
- for ops in opmap.itervalues():
+ for ops in opmap.values():
for op in ops:
# calls __bool__, which should fail
self.assertRaises(TypeError, bool, op(a, b))
@@ -150,7 +150,7 @@ class NumberTest(unittest.TestCase):
continue # the combination int, int is useless
ta = typea(a)
tb = typeb(b)
- for ops in opmap.itervalues():
+ for ops in opmap.values():
for op in ops:
realoutcome = op(a, b)
testoutcome = op(ta, tb)
diff --git a/Lib/test/test_site.py b/Lib/test/test_site.py
index 6f32fcaa0b..11bb674a34 100644
--- a/Lib/test/test_site.py
+++ b/Lib/test/test_site.py
@@ -204,7 +204,7 @@ class ImportSideEffectTests(unittest.TestCase):
if sys.platform == "win32":
import locale
if locale.getdefaultlocale()[1].startswith('cp'):
- for value in encodings.aliases.aliases.itervalues():
+ for value in encodings.aliases.aliases.values():
if value == "mbcs":
break
else:
diff --git a/Lib/test/test_support.py b/Lib/test/test_support.py
index 6cc52ea05b..8b5f73cef7 100644
--- a/Lib/test/test_support.py
+++ b/Lib/test/test_support.py
@@ -239,8 +239,7 @@ def vereq(a, b):
def sortdict(dict):
"Like repr(dict), but in sorted order."
- items = dict.items()
- items.sort()
+ items = sorted(dict.items())
reprpairs = ["%r: %r" % pair for pair in items]
withcommas = ", ".join(reprpairs)
return "{%s}" % withcommas
@@ -305,7 +304,7 @@ class EnvironmentVarGuard(object):
return self
def __exit__(self, *ignore_exc):
- for envvar, value in self._reset.iteritems():
+ for envvar, value in self._reset.items():
self._environ[envvar] = value
for unset in self._unset:
del self._environ[unset]
diff --git a/Lib/test/test_urllib2.py b/Lib/test/test_urllib2.py
index 0ea606fd2d..6187dade5b 100644
--- a/Lib/test/test_urllib2.py
+++ b/Lib/test/test_urllib2.py
@@ -90,8 +90,7 @@ def test_request_headers_methods():
>>> r.header_items()
[('Spam-eggs', 'blah')]
>>> r.add_header("Foo-Bar", "baz")
- >>> items = r.header_items()
- >>> items.sort()
+ >>> items = sorted(r.header_items())
>>> items
[('Foo-bar', 'baz'), ('Spam-eggs', 'blah')]
@@ -235,7 +234,7 @@ class MockFile:
class MockHeaders(dict):
def getheaders(self, name):
- return self.values()
+ return list(self.values())
class MockResponse(StringIO.StringIO):
def __init__(self, code, msg, headers, data, url=None):
diff --git a/Lib/test/test_userdict.py b/Lib/test/test_userdict.py
index a7fc60aa5d..05d6d9ea7a 100644
--- a/Lib/test/test_userdict.py
+++ b/Lib/test/test_userdict.py
@@ -208,7 +208,7 @@ class SeqDict(UserDict.DictMixin):
if other is not None:
for (key, value) in other:
self[key] = value
- for (key, value) in kwargs.iteritems():
+ for (key, value) in kwargs.items():
self[key] = value
def __getitem__(self, key):
try:
@@ -234,7 +234,7 @@ class SeqDict(UserDict.DictMixin):
return list(self.keylist)
def copy(self):
d = self.__class__()
- for key, value in self.iteritems():
+ for key, value in self.items():
d[key] = value
return d
@classmethod
@@ -278,13 +278,13 @@ class UserDictMixinTest(mapping_tests.TestMappingProtocol):
self.assertEqual(len(s), 2)
# iteritems
- self.assertEqual(list(s.iteritems()), [(10,'ten'), (30, 'thirty')])
+ self.assertEqual(list(s.items()), [(10,'ten'), (30, 'thirty')])
# iterkeys
- self.assertEqual(list(s.iterkeys()), [10, 30])
+ self.assertEqual(list(s.keys()), [10, 30])
# itervalues
- self.assertEqual(list(s.itervalues()), ['ten', 'thirty'])
+ self.assertEqual(list(s.values()), ['ten', 'thirty'])
# values
self.assertEqual(s.values(), ['ten', 'thirty'])
diff --git a/Lib/test/test_uuid.py b/Lib/test/test_uuid.py
index 3e5f77d4c9..ad3b0b3b68 100644
--- a/Lib/test/test_uuid.py
+++ b/Lib/test/test_uuid.py
@@ -295,7 +295,7 @@ class TestUUID(TestCase):
if TestUUID.last_node:
if TestUUID.last_node != node:
msg = "different sources disagree on node:\n"
- for s, n in TestUUID.source2node.iteritems():
+ for s, n in TestUUID.source2node.items():
msg += " from source %r, node was %012x\n" % (s, n)
# There's actually no reason to expect the MAC addresses
# to agree across various methods -- e.g., a box may have
diff --git a/Lib/test/test_weakref.py b/Lib/test/test_weakref.py
index 76169f7af7..1213b572a1 100644
--- a/Lib/test/test_weakref.py
+++ b/Lib/test/test_weakref.py
@@ -839,7 +839,7 @@ class MappingTestCase(TestBase):
def check_iters(self, dict):
# item iterator:
items = dict.items()
- for item in dict.iteritems():
+ for item in dict.items():
items.remove(item)
self.assert_(len(items) == 0, "iteritems() did not touch all items")
@@ -851,13 +851,13 @@ class MappingTestCase(TestBase):
# key iterator, via iterkeys():
keys = dict.keys()
- for k in dict.iterkeys():
+ for k in dict.keys():
keys.remove(k)
self.assert_(len(keys) == 0, "iterkeys() did not touch all keys")
# value iterator:
values = dict.values()
- for v in dict.itervalues():
+ for v in dict.values():
values.remove(v)
self.assert_(len(values) == 0,
"itervalues() did not touch all values")
@@ -1093,7 +1093,7 @@ None
... def __init__(self, ob, callback=None, **annotations):
... super(ExtendedRef, self).__init__(ob, callback)
... self.__counter = 0
-... for k, v in annotations.iteritems():
+... for k, v in annotations.items():
... setattr(self, k, v)
... def __call__(self):
... '''Return a pair containing the referent and the number of
@@ -1104,7 +1104,7 @@ None
... self.__counter += 1
... ob = (ob, self.__counter)
... return ob
-...
+...
>>> class A: # not in docs from here, just testing the ExtendedRef
... pass
...
diff --git a/Lib/test/test_xmlrpc.py b/Lib/test/test_xmlrpc.py
index 795e097949..0798fa1b6b 100644
--- a/Lib/test/test_xmlrpc.py
+++ b/Lib/test/test_xmlrpc.py
@@ -145,7 +145,7 @@ class XMLRPCTestCase(unittest.TestCase):
if not setdefaultencoding_existed:
del sys.setdefaultencoding
- items = d.items()
+ items = list(d.items())
if have_unicode:
self.assertEquals(s, u"abc \x95")
self.assert_(isinstance(s, unicode))
diff --git a/Lib/threading.py b/Lib/threading.py
index e23007e92f..439a3784f8 100644
--- a/Lib/threading.py
+++ b/Lib/threading.py
@@ -707,7 +707,7 @@ def activeCount():
def enumerate():
_active_limbo_lock.acquire()
- active = _active.values() + _limbo.values()
+ active = list(_active.values()) + list(_limbo.values())
_active_limbo_lock.release()
return active
diff --git a/Lib/token.py b/Lib/token.py
index 477827ac0a..cacd14dc33 100755
--- a/Lib/token.py
+++ b/Lib/token.py
@@ -68,7 +68,7 @@ NT_OFFSET = 256
#--end constants--
tok_name = {}
-for _name, _value in globals().items():
+for _name, _value in list(globals().items()):
if type(_value) is type(0):
tok_name[_value] = _name
diff --git a/Lib/trace.py b/Lib/trace.py
index b2ec557461..0f89c157e8 100644
--- a/Lib/trace.py
+++ b/Lib/trace.py
@@ -282,7 +282,7 @@ class CoverageResults:
# accumulate summary info, if needed
sums = {}
- for filename, count in per_file.iteritems():
+ for filename, count in per_file.items():
# skip some "files" we don't care about...
if filename == "<string>":
continue
diff --git a/Lib/urllib2.py b/Lib/urllib2.py
index 058397d7f8..60ff2609bd 100644
--- a/Lib/urllib2.py
+++ b/Lib/urllib2.py
@@ -281,7 +281,7 @@ class Request:
def header_items(self):
hdrs = self.unredirected_hdrs.copy()
hdrs.update(self.headers)
- return hdrs.items()
+ return list(hdrs.items())
class OpenerDirector:
def __init__(self):
@@ -710,7 +710,7 @@ class HTTPPasswordMgr:
domains = self.passwd.get(realm, {})
for default_port in True, False:
reduced_authuri = self.reduce_uri(authuri, default_port)
- for uris, authinfo in domains.iteritems():
+ for uris, authinfo in domains.items():
for uri in uris:
if self.is_suburi(uri, reduced_authuri):
return authinfo
@@ -1318,21 +1318,21 @@ class CacheFTPHandler(FTPHandler):
# first check for old ones
t = time.time()
if self.soonest <= t:
- for k, v in self.timeout.items():
+ for k, v in list(self.timeout.items()):
if v < t:
self.cache[k].close()
del self.cache[k]
del self.timeout[k]
- self.soonest = min(self.timeout.values())
+ self.soonest = min(list(self.timeout.values()))
# then check the size
if len(self.cache) == self.max_conns:
- for k, v in self.timeout.items():
+ for k, v in list(self.timeout.items()):
if v == self.soonest:
del self.cache[k]
del self.timeout[k]
break
- self.soonest = min(self.timeout.values())
+ self.soonest = min(list(self.timeout.values()))
class GopherHandler(BaseHandler):
def gopher_open(self, req):
diff --git a/Lib/weakref.py b/Lib/weakref.py
index 44cf9a7c1a..0122da4d7b 100644
--- a/Lib/weakref.py
+++ b/Lib/weakref.py
@@ -100,16 +100,16 @@ class WeakValueDictionary(UserDict.UserDict):
return L
def iteritems(self):
- for wr in self.data.itervalues():
+ for wr in self.data.values():
value = wr()
if value is not None:
yield wr.key, value
def iterkeys(self):
- return self.data.iterkeys()
+ return self.data.keys()
def __iter__(self):
- return self.data.iterkeys()
+ return self.data.keys()
def itervaluerefs(self):
"""Return an iterator that yields the weak references to the values.
@@ -121,10 +121,10 @@ class WeakValueDictionary(UserDict.UserDict):
keep the values around longer than needed.
"""
- return self.data.itervalues()
+ return self.data.values()
def itervalues(self):
- for wr in self.data.itervalues():
+ for wr in self.data.values():
obj = wr()
if obj is not None:
yield obj
@@ -268,7 +268,7 @@ class WeakKeyDictionary(UserDict.UserDict):
return L
def iteritems(self):
- for wr, value in self.data.iteritems():
+ for wr, value in self.data.items():
key = wr()
if key is not None:
yield key, value
@@ -283,19 +283,19 @@ class WeakKeyDictionary(UserDict.UserDict):
keep the keys around longer than needed.
"""
- return self.data.iterkeys()
+ return self.data.keys()
def iterkeys(self):
- for wr in self.data.iterkeys():
+ for wr in self.data.keys():
obj = wr()
if obj is not None:
yield obj
def __iter__(self):
- return self.iterkeys()
+ return self.keys()
def itervalues(self):
- return self.data.itervalues()
+ return self.data.values()
def keyrefs(self):
"""Return a list of weak references to the keys.
diff --git a/Lib/xml/etree/ElementTree.py b/Lib/xml/etree/ElementTree.py
index e03e297050..aed69bbd05 100644
--- a/Lib/xml/etree/ElementTree.py
+++ b/Lib/xml/etree/ElementTree.py
@@ -645,7 +645,7 @@ class ElementTree:
elif tag is ProcessingInstruction:
file.write("<?%s?>" % _escape_cdata(node.text, encoding))
else:
- items = node.items()
+ items = list(node.items())
xmlns_items = [] # new namespaces in this scope
try:
if isinstance(tag, QName) or tag[:1] == "{":
diff --git a/Misc/NEWS b/Misc/NEWS
index cda848bd3a..72a7d84ebf 100644
--- a/Misc/NEWS
+++ b/Misc/NEWS
@@ -36,6 +36,9 @@ TO DO
Core and Builtins
-----------------
+- PEP 3106: dict.iterkeys(), .iteritems(), .itervalues() are now gone;
+ and .keys(), .items(), .values() return dict views.
+
- PEP 3105: print is now a function. Also (not in the PEP) the
'softspace' attribute of files is now gone (since print() doesn't use
it). A side effect of this change is that you can get incomplete
diff --git a/Modules/cPickle.c b/Modules/cPickle.c
index 98ab500aa3..ad2b91fee5 100644
--- a/Modules/cPickle.c
+++ b/Modules/cPickle.c
@@ -1752,7 +1752,7 @@ save_dict(Picklerobject *self, PyObject *args)
int res = -1;
char s[3];
int len;
- PyObject *iter;
+ PyObject *items, *iter;
if (self->fast && !fast_save_enter(self, args))
goto finally;
@@ -1784,7 +1784,11 @@ save_dict(Picklerobject *self, PyObject *args)
goto finally;
/* Materialize the dict items. */
- iter = PyObject_CallMethod(args, "iteritems", "()");
+ items = PyObject_CallMethod(args, "items", "()");
+ if (items == NULL)
+ goto finally;
+ iter = PyObject_GetIter(items);
+ Py_DECREF(items);
if (iter == NULL)
goto finally;
res = batch_dict(self, iter);
diff --git a/Modules/collectionsmodule.c b/Modules/collectionsmodule.c
index 9fff7f0896..f75e1a320a 100644
--- a/Modules/collectionsmodule.c
+++ b/Modules/collectionsmodule.c
@@ -1140,6 +1140,7 @@ defdict_reduce(defdictobject *dd)
*/
PyObject *args;
PyObject *items;
+ PyObject *iteritems;
PyObject *result;
if (dd->default_factory == NULL || dd->default_factory == Py_None)
args = PyTuple_New(0);
@@ -1147,14 +1148,20 @@ defdict_reduce(defdictobject *dd)
args = PyTuple_Pack(1, dd->default_factory);
if (args == NULL)
return NULL;
- items = PyObject_CallMethod((PyObject *)dd, "iteritems", "()");
+ items = PyObject_CallMethod((PyObject *)dd, "items", "()");
if (items == NULL) {
Py_DECREF(args);
return NULL;
}
- result = PyTuple_Pack(5, dd->dict.ob_type, args,
- Py_None, Py_None, items);
+ iteritems = PyObject_GetIter(items);
Py_DECREF(items);
+ if (iteritems == NULL) {
+ Py_DECREF(args);
+ return NULL;
+ }
+ result = PyTuple_Pack(5, dd->dict.ob_type, args,
+ Py_None, Py_None, iteritems);
+ Py_DECREF(iteritems);
Py_DECREF(args);
return result;
}
diff --git a/Objects/abstract.c b/Objects/abstract.c
index 8405782b44..4e5838fa05 100644
--- a/Objects/abstract.c
+++ b/Objects/abstract.c
@@ -1657,6 +1657,54 @@ PyMapping_HasKey(PyObject *o, PyObject *key)
return 0;
}
+PyObject *
+PyMapping_Keys(PyObject *o)
+{
+ PyObject *keys;
+ PyObject *fast;
+
+ if (PyDict_CheckExact(o))
+ return PyDict_Keys(o);
+ keys = PyObject_CallMethod(o, "keys", NULL);
+ if (keys == NULL)
+ return NULL;
+ fast = PySequence_Fast(keys, "o.keys() are not iterable");
+ Py_DECREF(keys);
+ return fast;
+}
+
+PyObject *
+PyMapping_Items(PyObject *o)
+{
+ PyObject *items;
+ PyObject *fast;
+
+ if (PyDict_CheckExact(o))
+ return PyDict_Items(o);
+ items = PyObject_CallMethod(o, "items", NULL);
+ if (items == NULL)
+ return NULL;
+ fast = PySequence_Fast(items, "o.items() are not iterable");
+ Py_DECREF(items);
+ return fast;
+}
+
+PyObject *
+PyMapping_Values(PyObject *o)
+{
+ PyObject *values;
+ PyObject *fast;
+
+ if (PyDict_CheckExact(o))
+ return PyDict_Values(o);
+ values = PyObject_CallMethod(o, "values", NULL);
+ if (values == NULL)
+ return NULL;
+ fast = PySequence_Fast(values, "o.values() are not iterable");
+ Py_DECREF(values);
+ return fast;
+}
+
/* Operations on callable objects */
/* XXX PyCallable_Check() is in object.c */
diff --git a/Objects/dictobject.c b/Objects/dictobject.c
index ec14fcbc31..49907b4f48 100644
--- a/Objects/dictobject.c
+++ b/Objects/dictobject.c
@@ -1760,6 +1760,7 @@ extern PyTypeObject PyDictIterValue_Type; /* Forward */
extern PyTypeObject PyDictIterItem_Type; /* Forward */
static PyObject *dictiter_new(dictobject *, PyTypeObject *);
+#if 0
static PyObject *
dict_iterkeys(dictobject *dict)
{
@@ -1777,6 +1778,7 @@ dict_iteritems(dictobject *dict)
{
return dictiter_new(dict, &PyDictIterItem_Type);
}
+#endif
PyDoc_STRVAR(contains__doc__,
@@ -1798,6 +1800,7 @@ PyDoc_STRVAR(popitem__doc__,
"D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\
2-tuple; but raise KeyError if D is empty");
+#if 0
PyDoc_STRVAR(keys__doc__,
"D.keys() -> list of D's keys");
@@ -1806,6 +1809,7 @@ PyDoc_STRVAR(items__doc__,
PyDoc_STRVAR(values__doc__,
"D.values() -> list of D's values");
+#endif
PyDoc_STRVAR(update__doc__,
"D.update(E, **F) -> None. Update D from E and F: for k in E: D[k] = E[k]\
@@ -1821,6 +1825,7 @@ PyDoc_STRVAR(clear__doc__,
PyDoc_STRVAR(copy__doc__,
"D.copy() -> a shallow copy of D");
+#if 0
PyDoc_STRVAR(iterkeys__doc__,
"D.iterkeys() -> an iterator over the keys of D");
@@ -1829,6 +1834,7 @@ PyDoc_STRVAR(itervalues__doc__,
PyDoc_STRVAR(iteritems__doc__,
"D.iteritems() -> an iterator over the (key, value) items of D");
+#endif
/* Forward */
static PyObject *dictkeys_new(PyObject *);
@@ -1852,18 +1858,20 @@ static PyMethodDef mapp_methods[] = {
pop__doc__},
{"popitem", (PyCFunction)dict_popitem, METH_NOARGS,
popitem__doc__},
+#if 0
{"keys", (PyCFunction)dict_keys, METH_NOARGS,
keys__doc__},
- {"KEYS", (PyCFunction)dictkeys_new, METH_NOARGS,
- KEYS__doc__},
- {"ITEMS", (PyCFunction)dictitems_new, METH_NOARGS,
- ITEMS__doc__},
- {"VALUES", (PyCFunction)dictvalues_new, METH_NOARGS,
- VALUES__doc__},
{"items", (PyCFunction)dict_items, METH_NOARGS,
items__doc__},
{"values", (PyCFunction)dict_values, METH_NOARGS,
values__doc__},
+#endif
+ {"keys", (PyCFunction)dictkeys_new, METH_NOARGS,
+ KEYS__doc__},
+ {"items", (PyCFunction)dictitems_new, METH_NOARGS,
+ ITEMS__doc__},
+ {"values", (PyCFunction)dictvalues_new, METH_NOARGS,
+ VALUES__doc__},
{"update", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS,
update__doc__},
{"fromkeys", (PyCFunction)dict_fromkeys, METH_VARARGS | METH_CLASS,
@@ -1872,12 +1880,14 @@ static PyMethodDef mapp_methods[] = {
clear__doc__},
{"copy", (PyCFunction)dict_copy, METH_NOARGS,
copy__doc__},
+#if 0
{"iterkeys", (PyCFunction)dict_iterkeys, METH_NOARGS,
iterkeys__doc__},
{"itervalues", (PyCFunction)dict_itervalues, METH_NOARGS,
itervalues__doc__},
{"iteritems", (PyCFunction)dict_iteritems, METH_NOARGS,
iteritems__doc__},
+#endif
{NULL, NULL} /* sentinel */
};
diff --git a/Objects/typeobject.c b/Objects/typeobject.c
index f716906749..cd211e6c49 100644
--- a/Objects/typeobject.c
+++ b/Objects/typeobject.c
@@ -2601,7 +2601,11 @@ reduce_2(PyObject *obj)
Py_INCREF(dictitems);
}
else {
- dictitems = PyObject_CallMethod(obj, "iteritems", "");
+ PyObject *items = PyObject_CallMethod(obj, "items", "");
+ if (items == NULL)
+ goto end;
+ dictitems = PyObject_GetIter(items);
+ Py_DECREF(items);
if (dictitems == NULL)
goto end;
}