- 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.
This commit is contained in:
Guido van Rossum 2007-02-11 06:12:03 +00:00
parent 4e66dfcdc4
commit cc2b016125
73 changed files with 317 additions and 272 deletions

View File

@ -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 or tuple of the keys in object o.
On success, return a list of the keys in object o. On On failure, return NULL.
failure, return NULL. This is equivalent to the Python
expression: o.keys().
*/ */
#define PyMapping_Keys(O) PyObject_CallMethod(O,"keys",NULL)
/* Implemented as macro: PyAPI_FUNC(PyObject *) PyMapping_Values(PyObject *o);
PyObject *PyMapping_Values(PyObject *o); /*
On success, return a list or tuple of the values in object o.
On success, return a list of the values in object o. On On failure, return NULL.
failure, return NULL. This is equivalent to the Python
expression: o.values().
*/ */
#define PyMapping_Values(O) PyObject_CallMethod(O,"values",NULL)
/* Implemented as macro: PyAPI_FUNC(PyObject *) PyMapping_Items(PyObject *o);
PyObject *PyMapping_Items(PyObject *o); /*
On success, return a list or tuple of the items in object o,
On success, return a list of the items in object o, where where each item is a tuple containing a key-value pair.
each item is a tuple containing a key-value pair. On On failure, return NULL.
failure, return NULL. This is equivalent to the Python
expression: o.items().
*/ */
#define PyMapping_Items(O) PyObject_CallMethod(O,"items",NULL)
PyAPI_FUNC(PyObject *) PyMapping_GetItemString(PyObject *o, char *key); PyAPI_FUNC(PyObject *) PyMapping_GetItemString(PyObject *o, char *key);

View File

@ -214,7 +214,7 @@ class RawConfigParser:
def sections(self): def sections(self):
"""Return a list of section names, excluding [DEFAULT]""" """Return a list of section names, excluding [DEFAULT]"""
# self._sections will never have [DEFAULT] in it # self._sections will never have [DEFAULT] in it
return self._sections.keys() return list(self._sections.keys())
def add_section(self, section): def add_section(self, section):
"""Create a new section in the configuration. """Create a new section in the configuration.
@ -242,7 +242,7 @@ class RawConfigParser:
opts.update(self._defaults) opts.update(self._defaults)
if '__name__' in opts: if '__name__' in opts:
del opts['__name__'] del opts['__name__']
return opts.keys() return list(opts.keys())
def read(self, filenames): def read(self, filenames):
"""Read and parse a filename or a list of filenames. """Read and parse a filename or a list of filenames.
@ -547,7 +547,7 @@ class ConfigParser(RawConfigParser):
if vars: if vars:
for key, value in vars.items(): for key, value in vars.items():
d[self.optionxform(key)] = value d[self.optionxform(key)] = value
options = d.keys() options = list(d.keys())
if "__name__" in options: if "__name__" in options:
options.remove("__name__") options.remove("__name__")
if raw: if raw:

View File

@ -488,8 +488,7 @@ class Morsel(dict):
# Now add any defined attributes # Now add any defined attributes
if attrs is None: if attrs is None:
attrs = self._reserved attrs = self._reserved
items = self.items() items = sorted(self.items())
items.sort()
for K,V in items: for K,V in items:
if V == "": continue if V == "": continue
if K not in attrs: 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"): def output(self, attrs=None, header="Set-Cookie:", sep="\015\012"):
"""Return a string suitable for HTTP.""" """Return a string suitable for HTTP."""
result = [] result = []
items = self.items() items = sorted(self.items())
items.sort()
for K,V in items: for K,V in items:
result.append( V.output(attrs, header) ) result.append( V.output(attrs, header) )
return sep.join(result) return sep.join(result)
@ -593,8 +591,7 @@ class BaseCookie(dict):
def __repr__(self): def __repr__(self):
L = [] L = []
items = self.items() items = sorted(self.items())
items.sort()
for K,V in items: for K,V in items:
L.append( '%s=%s' % (K,repr(V.value) ) ) L.append( '%s=%s' % (K,repr(V.value) ) )
return '<%s: %s>' % (self.__class__.__name__, _spacejoin(L)) return '<%s: %s>' % (self.__class__.__name__, _spacejoin(L))
@ -602,8 +599,7 @@ class BaseCookie(dict):
def js_output(self, attrs=None): def js_output(self, attrs=None):
"""Return a string suitable for JavaScript.""" """Return a string suitable for JavaScript."""
result = [] result = []
items = self.items() items = sorted(self.items())
items.sort()
for K,V in items: for K,V in items:
result.append( V.js_output(attrs) ) result.append( V.js_output(attrs) )
return _nulljoin(result) return _nulljoin(result)

View File

@ -42,9 +42,9 @@ class UserDict:
return c return c
def keys(self): return self.data.keys() def keys(self): return self.data.keys()
def items(self): return self.data.items() def items(self): return self.data.items()
def iteritems(self): return self.data.iteritems() def iteritems(self): return self.data.items()
def iterkeys(self): return self.data.iterkeys() def iterkeys(self): return self.data.keys()
def itervalues(self): return self.data.itervalues() def itervalues(self): return self.data.values()
def values(self): return self.data.values() def values(self): return self.data.values()
def update(self, dict=None, **kwargs): def update(self, dict=None, **kwargs):
if dict is None: if dict is None:
@ -111,12 +111,12 @@ class DictMixin:
# fourth level uses definitions from lower levels # fourth level uses definitions from lower levels
def itervalues(self): def itervalues(self):
for _, v in self.iteritems(): for _, v in self.items():
yield v yield v
def values(self): def values(self):
return [v for _, v in self.iteritems()] return [v for _, v in self.items()]
def items(self): def items(self):
return list(self.iteritems()) return list(self.items())
def clear(self): def clear(self):
for key in self.keys(): for key in self.keys():
del self[key] del self[key]
@ -140,7 +140,7 @@ class DictMixin:
return value return value
def popitem(self): def popitem(self):
try: try:
k, v = self.iteritems().next() k, v = self.items().next()
except StopIteration: except StopIteration:
raise KeyError, 'container is empty' raise KeyError, 'container is empty'
del self[k] del self[k]
@ -152,6 +152,9 @@ class DictMixin:
elif hasattr(other, 'iteritems'): # iteritems saves memory and lookups elif hasattr(other, 'iteritems'): # iteritems saves memory and lookups
for k, v in other.iteritems(): for k, v in other.iteritems():
self[k] = v 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'): elif hasattr(other, 'keys'):
for k in other.keys(): for k in other.keys():
self[k] = other[k] self[k] = other[k]
@ -166,14 +169,14 @@ class DictMixin:
except KeyError: except KeyError:
return default return default
def __repr__(self): def __repr__(self):
return repr(dict(self.iteritems())) return repr(dict(self.items()))
def __eq__(self, other): def __eq__(self, other):
if isinstance(other, DictMixin): if isinstance(other, DictMixin):
other = dict(other.iteritems()) other = dict(other.items())
return dict(self.iteritems()) == other return dict(self.items()) == other
def __ne__(self, other): def __ne__(self, other):
if isinstance(other, DictMixin): if isinstance(other, DictMixin):
other = dict(other.iteritems()) other = dict(other.items())
return dict(self.iteritems()) != other return dict(self.items()) != other
def __len__(self): def __len__(self):
return len(self.keys()) return len(self.keys())

View File

@ -37,8 +37,7 @@ def lwp_cookie_str(cookie):
if cookie.comment: h.append(("comment", cookie.comment)) if cookie.comment: h.append(("comment", cookie.comment))
if cookie.comment_url: h.append(("commenturl", cookie.comment_url)) if cookie.comment_url: h.append(("commenturl", cookie.comment_url))
keys = cookie._rest.keys() keys = sorted(cookie._rest.keys())
keys.sort()
for k in keys: for k in keys:
h.append((k, str(cookie._rest[k]))) h.append((k, str(cookie._rest[k])))

View File

@ -338,7 +338,7 @@ def strptime(data_string, format="%a %b %d %H:%M:%S %Y"):
# values # values
weekday = julian = -1 weekday = julian = -1
found_dict = found.groupdict() found_dict = found.groupdict()
for group_key in found_dict.iterkeys(): for group_key in found_dict.keys():
# Directives not explicitly handled below: # Directives not explicitly handled below:
# c, x, X # c, x, X
# handled by making out of other directives # handled by making out of other directives

View File

@ -28,8 +28,7 @@ local to a thread. If we access the data in a different thread:
>>> log = [] >>> log = []
>>> def f(): >>> def f():
... items = mydata.__dict__.items() ... items = sorted(mydata.__dict__.items())
... items.sort()
... log.append(items) ... log.append(items)
... mydata.number = 11 ... mydata.number = 11
... log.append(mydata.number) ... log.append(mydata.number)

View File

@ -126,9 +126,7 @@ _b32alphabet = {
8: 'I', 17: 'R', 26: '2', 8: 'I', 17: 'R', 26: '2',
} }
_b32tab = _b32alphabet.items() _b32tab = [v for k, v in sorted(_b32alphabet.items())]
_b32tab.sort()
_b32tab = [v for k, v in _b32tab]
_b32rev = dict([(v, int(k)) for k, v in _b32alphabet.items()]) _b32rev = dict([(v, int(k)) for k, v in _b32alphabet.items()])

View File

@ -1337,6 +1337,6 @@ class Yield(Node):
def __repr__(self): def __repr__(self):
return "Yield(%s)" % (repr(self.value),) 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): if isinstance(obj, type) and issubclass(obj, Node):
nodes[name.lower()] = obj nodes[name.lower()] = obj

View File

@ -18,7 +18,7 @@ class Set:
def add(self, elt): def add(self, elt):
self.elts[elt] = elt self.elts[elt] = elt
def elements(self): def elements(self):
return self.elts.keys() return list(self.elts.keys())
def has_elt(self, elt): def has_elt(self, elt):
return elt in self.elts return elt in self.elts
def remove(self, elt): def remove(self, elt):

View File

@ -504,7 +504,7 @@ class PyFlowGraph(FlowGraph):
if name in cells] if name in cells]
for name in self.cellvars: for name in self.cellvars:
del cells[name] del cells[name]
self.cellvars = self.cellvars + cells.keys() self.cellvars = self.cellvars + list(cells.keys())
self.closure = self.cellvars + self.freevars self.closure = self.cellvars + self.freevars
def _lookupName(self, name, list): def _lookupName(self, name, list):
@ -573,7 +573,7 @@ class PyFlowGraph(FlowGraph):
# similarly for other opcodes... # similarly for other opcodes...
for name, obj in locals().items(): for name, obj in list(locals().items()):
if name[:9] == "_convert_": if name[:9] == "_convert_":
opname = name[9:] opname = name[9:]
_converters[opname] = obj _converters[opname] = obj

View File

@ -1171,8 +1171,7 @@ class DefaultCookiePolicy(CookiePolicy):
def vals_sorted_by_key(adict): def vals_sorted_by_key(adict):
keys = adict.keys() keys = sorted(adict.keys())
keys.sort()
return map(adict.get, keys) return map(adict.get, keys)
def deepvalues(mapping): def deepvalues(mapping):

View File

@ -230,7 +230,7 @@ d[tuple] = _deepcopy_tuple
def _deepcopy_dict(x, memo): def _deepcopy_dict(x, memo):
y = {} y = {}
memo[id(x)] = y memo[id(x)] = y
for key, value in x.iteritems(): for key, value in x.items():
y[deepcopy(key, memo)] = deepcopy(value, memo) y[deepcopy(key, memo)] = deepcopy(value, memo)
return y return y
d[dict] = _deepcopy_dict d[dict] = _deepcopy_dict
@ -302,7 +302,7 @@ def _reconstruct(x, info, deep, memo=None):
if state is not None: if state is not None:
y.__dict__.update(state) y.__dict__.update(state)
if slotstate is not None: if slotstate is not None:
for key, value in slotstate.iteritems(): for key, value in slotstate.items():
setattr(y, key, value) setattr(y, key, value)
return y return y
@ -337,7 +337,7 @@ def _test():
def __getstate__(self): def __getstate__(self):
return {'a': self.a, 'arg': self.arg} return {'a': self.a, 'arg': self.arg}
def __setstate__(self, state): def __setstate__(self, state):
for key, value in state.iteritems(): for key, value in state.items():
setattr(self, key, value) setattr(self, key, value)
def __deepcopy__(self, memo=None): def __deepcopy__(self, memo=None):
new = self.__class__(deepcopy(self.arg, memo)) new = self.__class__(deepcopy(self.arg, memo))

View File

@ -278,7 +278,7 @@ class Sniffer:
charFrequency[char] = metaFrequency charFrequency[char] = metaFrequency
for char in charFrequency.keys(): for char in charFrequency.keys():
items = charFrequency[char].items() items = list(charFrequency[char].items())
if len(items) == 1 and items[0][0] == 0: if len(items) == 1 and items[0][0] == 0:
continue continue
# get the mode of the frequencies # get the mode of the frequencies
@ -308,7 +308,7 @@ class Sniffer:
consistency -= 0.01 consistency -= 0.01
if len(delims) == 1: if len(delims) == 1:
delim = delims.keys()[0] delim = list(delims.keys())[0]
skipinitialspace = (data[0].count(delim) == skipinitialspace = (data[0].count(delim) ==
data[0].count("%c " % delim)) data[0].count("%c " % delim))
return (delim, skipinitialspace) return (delim, skipinitialspace)
@ -367,7 +367,7 @@ class Sniffer:
if len(row) != columns: if len(row) != columns:
continue # skip rows that have irregular number of 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]: for thisType in [int, int, float, complex]:
try: try:

View File

@ -41,7 +41,7 @@ def find_package_modules(package, mask):
hasattr(package.__loader__, '_files')): hasattr(package.__loader__, '_files')):
path = package.__name__.replace(".", os.path.sep) path = package.__name__.replace(".", os.path.sep)
mask = os.path.join(path, mask) 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): if fnmatch.fnmatchcase(fnm, mask):
yield os.path.splitext(fnm)[0].replace(os.path.sep, ".") yield os.path.splitext(fnm)[0].replace(os.path.sep, ".")
else: else:

View File

@ -331,7 +331,7 @@ class SequenceMatcher:
junkdict = {} junkdict = {}
if isjunk: if isjunk:
for d in populardict, b2j: for d in populardict, b2j:
for elt in d.keys(): for elt in list(d.keys()):
if isjunk(elt): if isjunk(elt):
junkdict[elt] = 1 junkdict[elt] = 1
del d[elt] del d[elt]

View File

@ -271,7 +271,7 @@ def parse_makefile(fn, g=None):
# do variable interpolation here # do variable interpolation here
while notdone: while notdone:
for name in notdone.keys(): for name in list(notdone):
value = notdone[name] value = notdone[name]
m = _findvar1_rx.search(value) or _findvar2_rx.search(value) m = _findvar1_rx.search(value) or _findvar2_rx.search(value)
if m: if m:

View File

@ -109,7 +109,7 @@ class _Database(UserDict.DictMixin):
f = self._open(self._dirfile, 'w') f = self._open(self._dirfile, 'w')
self._chmod(self._dirfile) 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.write("%r, %r\n" % (key, pos_and_siz_pair))
f.close() f.close()
@ -202,7 +202,7 @@ class _Database(UserDict.DictMixin):
return key in self._index return key in self._index
def iterkeys(self): def iterkeys(self):
return self._index.iterkeys() return self._index.keys()
__iter__ = iterkeys __iter__ = iterkeys
def __len__(self): def __len__(self):

View File

@ -17,8 +17,7 @@ def segregate(str):
base.append(c) base.append(c)
else: else:
extended[c] = 1 extended[c] = 1
extended = extended.keys() extended = sorted(extended.keys())
extended.sort()
return "".join(base).encode("ascii"),extended return "".join(base).encode("ascii"),extended
def selective_len(str, max): def selective_len(str, max):

View File

@ -187,7 +187,7 @@ class dircmp:
def phase4_closure(self): # Recursively call phase4() on subdirectories def phase4_closure(self): # Recursively call phase4() on subdirectories
self.phase4() self.phase4()
for sd in self.subdirs.itervalues(): for sd in self.subdirs.values():
sd.phase4_closure() sd.phase4_closure()
def report(self): # Print a report on the differences between a and b 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 def report_partial_closure(self): # Print reports on self and on subdirs
self.report() self.report()
for sd in self.subdirs.itervalues(): for sd in self.subdirs.values():
print() print()
sd.report() sd.report()
def report_full_closure(self): # Report on self and subdirs recursively def report_full_closure(self): # Report on self and subdirs recursively
self.report() self.report()
for sd in self.subdirs.itervalues(): for sd in self.subdirs.values():
print() print()
sd.report_full_closure() sd.report_full_closure()

View File

@ -263,7 +263,7 @@ codepoint2name = {}
# (or a character reference if the character is outside the Latin-1 range) # (or a character reference if the character is outside the Latin-1 range)
entitydefs = {} entitydefs = {}
for (name, codepoint) in name2codepoint.iteritems(): for (name, codepoint) in name2codepoint.items():
codepoint2name[codepoint] = name codepoint2name[codepoint] = name
if codepoint <= 0xff: if codepoint <= 0xff:
entitydefs[name] = chr(codepoint) entitydefs[name] = chr(codepoint)

View File

@ -611,7 +611,7 @@ class HTTPResponse:
"""Return list of (header, value) tuples.""" """Return list of (header, value) tuples."""
if self.msg is None: if self.msg is None:
raise ResponseNotReady() raise ResponseNotReady()
return self.msg.items() return list(self.msg.items())
class HTTPConnection: class HTTPConnection:
@ -902,7 +902,7 @@ class HTTPConnection:
if thelen is not None: if thelen is not None:
self.putheader('Content-Length',thelen) self.putheader('Content-Length',thelen)
for hdr, value in headers.iteritems(): for hdr, value in headers.items():
self.putheader(hdr, value) self.putheader(hdr, value)
self.endheaders() self.endheaders()

View File

@ -95,11 +95,11 @@ class Mailbox:
def keys(self): def keys(self):
"""Return a list of keys.""" """Return a list of keys."""
return list(self.iterkeys()) return list(self.keys())
def itervalues(self): def itervalues(self):
"""Return an iterator over all messages.""" """Return an iterator over all messages."""
for key in self.iterkeys(): for key in self.keys():
try: try:
value = self[key] value = self[key]
except KeyError: except KeyError:
@ -107,15 +107,15 @@ class Mailbox:
yield value yield value
def __iter__(self): def __iter__(self):
return self.itervalues() return self.values()
def values(self): def values(self):
"""Return a list of messages. Memory intensive.""" """Return a list of messages. Memory intensive."""
return list(self.itervalues()) return list(self.values())
def iteritems(self): def iteritems(self):
"""Return an iterator over (key, message) tuples.""" """Return an iterator over (key, message) tuples."""
for key in self.iterkeys(): for key in self.keys():
try: try:
value = self[key] value = self[key]
except KeyError: except KeyError:
@ -124,7 +124,7 @@ class Mailbox:
def items(self): def items(self):
"""Return a list of (key, message) tuples. Memory intensive.""" """Return a list of (key, message) tuples. Memory intensive."""
return list(self.iteritems()) return list(self.items())
def __contains__(self, key): def __contains__(self, key):
"""Return True if the keyed message exists, False otherwise.""" """Return True if the keyed message exists, False otherwise."""
@ -136,7 +136,7 @@ class Mailbox:
def clear(self): def clear(self):
"""Delete all messages.""" """Delete all messages."""
for key in self.iterkeys(): for key in self.keys():
self.discard(key) self.discard(key)
def pop(self, key, default=None): def pop(self, key, default=None):
@ -150,7 +150,7 @@ class Mailbox:
def popitem(self): def popitem(self):
"""Delete an arbitrary (key, message) pair and return it.""" """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. return (key, self.pop(key)) # This is only run once.
else: else:
raise KeyError('No messages in mailbox') raise KeyError('No messages in mailbox')
@ -158,7 +158,7 @@ class Mailbox:
def update(self, arg=None): def update(self, arg=None):
"""Change the messages that correspond to certain keys.""" """Change the messages that correspond to certain keys."""
if hasattr(arg, 'iteritems'): if hasattr(arg, 'iteritems'):
source = arg.iteritems() source = arg.items()
elif hasattr(arg, 'items'): elif hasattr(arg, 'items'):
source = arg.items() source = arg.items()
else: else:
@ -477,7 +477,7 @@ class Maildir(Mailbox):
def next(self): def next(self):
"""Return the next message in a one-time iteration.""" """Return the next message in a one-time iteration."""
if not hasattr(self, '_onetime_keys'): if not hasattr(self, '_onetime_keys'):
self._onetime_keys = self.iterkeys() self._onetime_keys = self.keys()
while True: while True:
try: try:
return self[self._onetime_keys.next()] return self[self._onetime_keys.next()]
@ -950,7 +950,7 @@ class MH(Mailbox):
def __len__(self): def __len__(self):
"""Return a count of messages in the mailbox.""" """Return a count of messages in the mailbox."""
return len(list(self.iterkeys())) return len(list(self.keys()))
def lock(self): def lock(self):
"""Lock the mailbox.""" """Lock the mailbox."""
@ -1038,7 +1038,7 @@ class MH(Mailbox):
f = open(os.path.join(self._path, '.mh_sequences'), 'r+') f = open(os.path.join(self._path, '.mh_sequences'), 'r+')
try: try:
os.close(os.open(f.name, os.O_WRONLY | os.O_TRUNC)) 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: if len(keys) == 0:
continue continue
f.write('%s:' % name) f.write('%s:' % name)
@ -1067,7 +1067,7 @@ class MH(Mailbox):
sequences = self.get_sequences() sequences = self.get_sequences()
prev = 0 prev = 0
changes = [] changes = []
for key in self.iterkeys(): for key in self.keys():
if key - 1 != prev: if key - 1 != prev:
changes.append((key, prev + 1)) changes.append((key, prev + 1))
if hasattr(os, 'link'): if hasattr(os, 'link'):
@ -1091,7 +1091,7 @@ class MH(Mailbox):
"""Inspect a new MHMessage and update sequences appropriately.""" """Inspect a new MHMessage and update sequences appropriately."""
pending_sequences = message.get_sequences() pending_sequences = message.get_sequences()
all_sequences = self.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: if name in pending_sequences:
key_list.append(key) key_list.append(key)
elif key in key_list: elif key in key_list:

View File

@ -24,7 +24,7 @@ def getcaps():
continue continue
morecaps = readmailcapfile(fp) morecaps = readmailcapfile(fp)
fp.close() fp.close()
for key, value in morecaps.iteritems(): for key, value in morecaps.items():
if not key in caps: if not key in caps:
caps[key] = value caps[key] = value
else: else:

View File

@ -314,7 +314,7 @@ class Folder:
"""Write the set of sequences back to the folder.""" """Write the set of sequences back to the folder."""
fullname = self.getsequencesfilename() fullname = self.getsequencesfilename()
f = None f = None
for key, seq in sequences.iteritems(): for key, seq in sequences.items():
s = IntSet('', ' ') s = IntSet('', ' ')
s.fromlist(seq) s.fromlist(seq)
if not f: f = open(fullname, 'w') if not f: f = open(fullname, 'w')

View File

@ -666,7 +666,7 @@ class Pickler:
write(MARK + DICT) write(MARK + DICT)
self.memoize(obj) self.memoize(obj)
self._batch_setitems(obj.iteritems()) self._batch_setitems(iter(obj.items()))
dispatch[DictionaryType] = save_dict dispatch[DictionaryType] = save_dict
if not PyStringMap is None: if not PyStringMap is None:

View File

@ -439,10 +439,10 @@ class Profile:
def snapshot_stats(self): def snapshot_stats(self):
self.stats = {} 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() callers = callers.copy()
nc = 0 nc = 0
for callcnt in callers.itervalues(): for callcnt in callers.values():
nc += callcnt nc += callcnt
self.stats[func] = cc, nc, tt, ct, callers self.stats[func] = cc, nc, tt, ct, callers

View File

@ -163,7 +163,7 @@ class Stats:
self.fcn_list = None self.fcn_list = None
for func, stat in other.stats.iteritems(): for func, stat in other.stats.items():
if func in self.stats: if func in self.stats:
old_func_stat = self.stats[func] old_func_stat = self.stats[func]
else: else:
@ -199,7 +199,7 @@ class Stats:
if not self.sort_arg_dict: if not self.sort_arg_dict:
self.sort_arg_dict = dict = {} self.sort_arg_dict = dict = {}
bad_list = {} bad_list = {}
for word, tup in self.sort_arg_dict_default.iteritems(): for word, tup in self.sort_arg_dict_default.items():
fragment = word fragment = word
while fragment: while fragment:
if not fragment: if not fragment:
@ -234,7 +234,7 @@ class Stats:
connector = ", " connector = ", "
stats_list = [] 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 + stats_list.append((cc, nc, tt, ct) + func +
(func_std_string(func), func)) (func_std_string(func), func))
@ -254,12 +254,12 @@ class Stats:
oldstats = self.stats oldstats = self.stats
self.stats = newstats = {} self.stats = newstats = {}
max_name_len = 0 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) newfunc = func_strip_path(func)
if len(func_std_string(newfunc)) > max_name_len: if len(func_std_string(newfunc)) > max_name_len:
max_name_len = len(func_std_string(newfunc)) max_name_len = len(func_std_string(newfunc))
newcallers = {} newcallers = {}
for func2, caller in callers.iteritems(): for func2, caller in callers.items():
newcallers[func_strip_path(func2)] = caller newcallers[func_strip_path(func2)] = caller
if newfunc in newstats: if newfunc in newstats:
@ -282,10 +282,10 @@ class Stats:
def calc_callees(self): def calc_callees(self):
if self.all_callees: return if self.all_callees: return
self.all_callees = all_callees = {} 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: if not func in all_callees:
all_callees[func] = {} all_callees[func] = {}
for func2, caller in callers.iteritems(): for func2, caller in callers.items():
if not func2 in all_callees: if not func2 in all_callees:
all_callees[func2] = {} all_callees[func2] = {}
all_callees[func2][func] = caller all_callees[func2][func] = caller
@ -394,9 +394,9 @@ class Stats:
print("Function ".ljust(name_size) + column_title, file=self.stream) print("Function ".ljust(name_size) + column_title, file=self.stream)
# print sub-header only if we have new-style callers # print sub-header only if we have new-style callers
subheader = False subheader = False
for cc, nc, tt, ct, callers in self.stats.itervalues(): for cc, nc, tt, ct, callers in self.stats.values():
if callers: if callers:
value = callers.itervalues().next() value = iter(callers.values()).next()
subheader = isinstance(value, tuple) subheader = isinstance(value, tuple)
break break
if subheader: if subheader:
@ -407,8 +407,7 @@ class Stats:
if not call_dict: if not call_dict:
print(file=self.stream) print(file=self.stream)
return return
clist = call_dict.keys() clist = sorted(call_dict.keys())
clist.sort()
indent = "" indent = ""
for func in clist: for func in clist:
name = func_std_string(func) name = func_std_string(func)
@ -508,9 +507,9 @@ def add_func_stats(target, source):
def add_callers(target, source): def add_callers(target, source):
"""Combine two caller lists in a single list.""" """Combine two caller lists in a single list."""
new_callers = {} new_callers = {}
for func, caller in target.iteritems(): for func, caller in target.items():
new_callers[func] = caller new_callers[func] = caller
for func, caller in source.iteritems(): for func, caller in source.items():
if func in new_callers: if func in new_callers:
new_callers[func] = caller + new_callers[func] new_callers[func] = caller + new_callers[func]
else: else:
@ -520,7 +519,7 @@ def add_callers(target, source):
def count_calls(callers): def count_calls(callers):
"""Sum the caller statistics to get total number of calls received.""" """Sum the caller statistics to get total number of calls received."""
nc = 0 nc = 0
for calls in callers.itervalues(): for calls in callers.values():
nc += calls nc += calls
return nc return nc
@ -642,7 +641,7 @@ if __name__ == '__main__':
self.stats.sort_stats(*line.split()) self.stats.sort_stats(*line.split())
else: else:
print("Valid sort keys (unique prefixes are accepted):", file=self.stream) 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) print("%s -- %s" % (key, value[1]), file=self.stream)
return 0 return 0
def help_sort(self): def help_sort(self):

View File

@ -329,7 +329,7 @@ def _main():
for obj in objs: for obj in objs:
if isinstance(obj, Class): if isinstance(obj, Class):
print("class", obj.name, obj.super, obj.lineno) 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: for name, lineno in methods:
if name != "__path__": if name != "__path__":
print(" def", name, lineno) print(" def", name, lineno)

View File

@ -437,18 +437,18 @@ class Message:
def keys(self): def keys(self):
"""Get all of a message's header field names.""" """Get all of a message's header field names."""
return self.dict.keys() return list(self.dict.keys())
def values(self): def values(self):
"""Get all of a message's header field values.""" """Get all of a message's header field values."""
return self.dict.values() return list(self.dict.values())
def items(self): def items(self):
"""Get all of a message's headers. """Get all of a message's headers.
Returns a list of name, value tuples. Returns a list of name, value tuples.
""" """
return self.dict.items() return list(self.dict.items())
def __str__(self): def __str__(self):
return ''.join(self.headers) return ''.join(self.headers)

View File

@ -144,7 +144,7 @@ class Shelf(UserDict.DictMixin):
def sync(self): def sync(self):
if self.writeback and self.cache: if self.writeback and self.cache:
self.writeback = False self.writeback = False
for key, entry in self.cache.iteritems(): for key, entry in self.cache.items():
self[key] = entry self[key] = entry
self.writeback = True self.writeback = True
self.cache = {} self.cache = {}

View File

@ -100,7 +100,7 @@ yield_expr = 342
#--end constants-- #--end constants--
sym_name = {} sym_name = {}
for _name, _value in globals().items(): for _name, _value in list(globals().items()):
if type(_value) is type(0): if type(_value) is type(0):
sym_name[_value] = _name sym_name[_value] = _name

View File

@ -13,7 +13,7 @@ __all__ = ["symtable", "SymbolTable", "newSymbolTable", "Class",
def symtable(code, filename, compile_type): def symtable(code, filename, compile_type):
raw = _symtable.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': if top.name == 'top':
break break
return newSymbolTable(top, filename) return newSymbolTable(top, filename)

View File

@ -51,8 +51,7 @@ class ForkWait(unittest.TestCase):
time.sleep(LONGSLEEP) time.sleep(LONGSLEEP)
a = self.alive.keys() a = sorted(self.alive.keys())
a.sort()
self.assertEquals(a, range(NUM_THREADS)) self.assertEquals(a, range(NUM_THREADS))
prefork_lives = self.alive.copy() prefork_lives = self.alive.copy()

View File

@ -73,13 +73,13 @@ class BasicTestMappingProtocol(unittest.TestCase):
self.assert_(hasattr(iter, '__iter__')) self.assert_(hasattr(iter, '__iter__'))
x = list(iter) x = list(iter)
self.assert_(set(x)==set(lst)==set(ref)) 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(iter(d), d.keys(), self.reference.keys())
check_iterandlist(d.itervalues(), d.values(), self.reference.values()) check_iterandlist(d.values(), d.values(), self.reference.values())
check_iterandlist(d.iteritems(), d.items(), self.reference.items()) check_iterandlist(d.items(), d.items(), self.reference.items())
#get #get
key, value = d.iteritems().next() key, value = d.items().next()
knownkey, knownvalue = self.other.iteritems().next() knownkey, knownvalue = self.other.items().next()
self.assertEqual(d.get(key, knownvalue), value) self.assertEqual(d.get(key, knownvalue), value)
self.assertEqual(d.get(knownkey, knownvalue), knownvalue) self.assertEqual(d.get(knownkey, knownvalue), knownvalue)
self.failIf(knownkey in d) self.failIf(knownkey in d)
@ -104,8 +104,8 @@ class BasicTestMappingProtocol(unittest.TestCase):
self.assertEqual(dict(p), self.reference) self.assertEqual(dict(p), self.reference)
d = self._full_mapping(self.reference) d = self._full_mapping(self.reference)
#setdefault #setdefault
key, value = d.iteritems().next() key, value = d.items().next()
knownkey, knownvalue = self.other.iteritems().next() knownkey, knownvalue = self.other.items().next()
self.assertEqual(d.setdefault(key, knownvalue), value) self.assertEqual(d.setdefault(key, knownvalue), value)
self.assertEqual(d[key], value) self.assertEqual(d[key], value)
self.assertEqual(d.setdefault(knownkey, knownvalue), knownvalue) self.assertEqual(d.setdefault(knownkey, knownvalue), knownvalue)
@ -183,7 +183,7 @@ class BasicTestMappingProtocol(unittest.TestCase):
# Iterator # Iterator
d = self._empty_mapping() d = self._empty_mapping()
d.update(self.other.iteritems()) d.update(self.other.items())
self.assertEqual(d.items(), self.other.items()) self.assertEqual(d.items(), self.other.items())
# FIXME: Doesn't work with UserDict # FIXME: Doesn't work with UserDict
@ -400,7 +400,7 @@ class TestMappingProtocol(BasicTestMappingProtocol):
# iterator # iterator
d = self._full_mapping({1:3, 2:4}) 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}) self.assertEqual(d, {1:2, 2:4, 3:4, 5:6})
class SimpleUserDict: class SimpleUserDict:

View File

@ -438,7 +438,7 @@ class AbstractPickleTests(unittest.TestCase):
for proto in protocols: for proto in protocols:
s = self.dumps(d, proto) s = self.dumps(d, proto)
x = self.loads(s) x = self.loads(s)
self.assertEqual(x.keys(), [1]) self.assertEqual(list(x.keys()), [1])
self.assert_(x[1] is x) self.assert_(x[1] is x)
def test_recursive_inst(self): def test_recursive_inst(self):
@ -461,7 +461,7 @@ class AbstractPickleTests(unittest.TestCase):
x = self.loads(s) x = self.loads(s)
self.assertEqual(len(x), 1) self.assertEqual(len(x), 1)
self.assertEqual(dir(x[0]), dir(i)) 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) self.assert_(x[0].attr[1] is x)
def test_garyp(self): def test_garyp(self):

View File

@ -40,7 +40,7 @@ class CommonTest(unittest.TestCase):
elif isinstance(obj, dict): elif isinstance(obj, dict):
return dict([ return dict([
(self.fixtype(key), self.fixtype(value)) (self.fixtype(key), self.fixtype(value))
for (key, value) in obj.iteritems() for (key, value) in obj.items()
]) ])
else: else:
return obj return obj

View File

@ -72,10 +72,8 @@ class AnyDBMTestCase(unittest.TestCase):
f.close() f.close()
def keys_helper(self, f): def keys_helper(self, f):
keys = f.keys() keys = sorted(f.keys())
keys.sort() dkeys = sorted(self._dict.keys())
dkeys = self._dict.keys()
dkeys.sort()
self.assertEqual(keys, dkeys) self.assertEqual(keys, dkeys)
return keys return keys

View File

@ -729,7 +729,7 @@ class CharacterTest(StringTest):
self.assertEqual(s.color, "blue") self.assertEqual(s.color, "blue")
s.color = "red" s.color = "red"
self.assertEqual(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): def test_nounicode(self):
a = array.array(self.typecode, self.example) a = array.array(self.typecode, self.example)

View File

@ -15,7 +15,7 @@ class TestBSDDB(unittest.TestCase):
def setUp(self): def setUp(self):
self.f = self.openmethod[0](self.fname, self.openflag, cachesize=32768) 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='') 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 self.f[k] = v
def tearDown(self): def tearDown(self):
@ -29,7 +29,7 @@ class TestBSDDB(unittest.TestCase):
pass pass
def test_getitem(self): def test_getitem(self):
for k, v in self.d.iteritems(): for k, v in self.d.items():
self.assertEqual(self.f[k], v) self.assertEqual(self.f[k], v)
def test_len(self): def test_len(self):
@ -48,7 +48,7 @@ class TestBSDDB(unittest.TestCase):
return return
self.f.close() self.f.close()
self.f = self.openmethod[0](self.fname, 'w') 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) self.assertEqual(self.f[k], v)
def assertSetEquals(self, seqn1, seqn2): def assertSetEquals(self, seqn1, seqn2):
@ -61,9 +61,9 @@ class TestBSDDB(unittest.TestCase):
self.assertSetEquals(d.keys(), f.keys()) self.assertSetEquals(d.keys(), f.keys())
self.assertSetEquals(d.values(), f.values()) self.assertSetEquals(d.values(), f.values())
self.assertSetEquals(d.items(), f.items()) self.assertSetEquals(d.items(), f.items())
self.assertSetEquals(d.iterkeys(), f.iterkeys()) self.assertSetEquals(d.keys(), f.keys())
self.assertSetEquals(d.itervalues(), f.itervalues()) self.assertSetEquals(d.values(), f.values())
self.assertSetEquals(d.iteritems(), f.iteritems()) self.assertSetEquals(d.items(), f.items())
def test_iter_while_modifying_values(self): def test_iter_while_modifying_values(self):
if not hasattr(self.f, '__iter__'): if not hasattr(self.f, '__iter__'):
@ -94,7 +94,7 @@ class TestBSDDB(unittest.TestCase):
if not hasattr(self.f, 'iteritems'): if not hasattr(self.f, 'iteritems'):
return return
di = self.d.iteritems() di = self.d.items()
while 1: while 1:
try: try:
k, v = di.next() k, v = di.next()
@ -105,7 +105,7 @@ class TestBSDDB(unittest.TestCase):
# it should behave the same as a dict. modifying values # it should behave the same as a dict. modifying values
# of existing keys should not break iteration. (adding # of existing keys should not break iteration. (adding
# or removing keys should) # or removing keys should)
fi = self.f.iteritems() fi = self.f.items()
while 1: while 1:
try: try:
k, v = fi.next() k, v = fi.next()
@ -159,7 +159,7 @@ class TestBSDDB(unittest.TestCase):
# test the iterator interface (if present) # test the iterator interface (if present)
if hasattr(self.f, 'iteritems'): if hasattr(self.f, 'iteritems'):
if debug: print("D") if debug: print("D")
i = self.f.iteritems() i = self.f.items()
k,v = i.next() k,v = i.next()
if debug: print("E") if debug: print("E")
self.f[k] = "please don't deadlock" self.f[k] = "please don't deadlock"
@ -198,7 +198,7 @@ class TestBSDDB(unittest.TestCase):
# do the bsddb._DBWithCursor _iter_mixin internals leak cursors? # do the bsddb._DBWithCursor _iter_mixin internals leak cursors?
nc1 = len(self.f._cursor_refs) nc1 = len(self.f._cursor_refs)
# create iterator # create iterator
i = self.f.iteritems() i = self.f.items()
nc2 = len(self.f._cursor_refs) nc2 = len(self.f._cursor_refs)
# use the iterator (should run to the first yeild, creating the cursor) # use the iterator (should run to the first yeild, creating the cursor)
k, v = i.next() k, v = i.next()
@ -240,7 +240,7 @@ class TestBSDDB(unittest.TestCase):
new = dict(y='life', u='of', i='brian') new = dict(y='life', u='of', i='brian')
self.f.update(new) self.f.update(new)
self.d.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) self.assertEqual(self.f[k], v)
def test_keyordering(self): def test_keyordering(self):

View File

@ -290,8 +290,8 @@ class BuiltinTest(unittest.TestCase):
if key == 'a': if key == 'a':
return 12 return 12
raise KeyError raise KeyError
def keys(self): def __iter__(self):
return list('xyz') return iter('xyz')
m = M() m = M()
g = globals() g = globals()
@ -313,8 +313,8 @@ class BuiltinTest(unittest.TestCase):
if key == 'a': if key == 'a':
return 12 return 12
return dict.__getitem__(self, key) return dict.__getitem__(self, key)
def keys(self): def __iter__(self):
return list('xyz') return iter('xyz')
d = D() d = D()
self.assertEqual(eval('a', g, d), 12) self.assertEqual(eval('a', g, d), 12)
@ -346,8 +346,8 @@ class BuiltinTest(unittest.TestCase):
class C: class C:
def __getitem__(self, item): def __getitem__(self, item):
raise KeyError(item) raise KeyError(item)
def keys(self): def __iter__(self):
return 'a' return 'a' # XXX Not quite faithful to the SF bug...
self.assertRaises(TypeError, eval, 'dir()', globals(), C()) self.assertRaises(TypeError, eval, 'dir()', globals(), C())
# Done outside of the method test_z to get the correct scope # Done outside of the method test_z to get the correct scope
@ -522,8 +522,8 @@ class BuiltinTest(unittest.TestCase):
unicode("123"): unicode("112233") unicode("123"): unicode("112233")
} }
for (cls, inps) in inputs.iteritems(): for (cls, inps) in inputs.items():
for (inp, exp) in inps.iteritems(): for (inp, exp) in inps.items():
# make sure the output goes through __getitem__ # make sure the output goes through __getitem__
# even if func is None # even if func is None
self.assertEqual( self.assertEqual(

View File

@ -7,18 +7,13 @@ from test import test_support
class SortedDict(UserDict.UserDict): class SortedDict(UserDict.UserDict):
def items(self): def items(self):
result = self.data.items() return sorted(self.data.items())
result.sort()
return result
def keys(self): def keys(self):
result = self.data.keys() return sorted(self.data.keys())
result.sort()
return result
def values(self): def values(self):
result = self.items() return [i[1] for i in self.items()]
return [i[1] for i in values]
def iteritems(self): return iter(self.items()) def iteritems(self): return iter(self.items())
def iterkeys(self): return iter(self.keys()) def iterkeys(self): return iter(self.keys())

View File

@ -118,9 +118,7 @@ parse_strict_test_cases = [
] ]
def norm(seq): def norm(seq):
if isinstance(seq, list): return sorted(seq, key=repr)
seq.sort(key=repr)
return seq
def first_elts(list): def first_elts(list):
return map(lambda x:x[0], list) return map(lambda x:x[0], list)

View File

@ -53,8 +53,8 @@ class TestSpecifics(unittest.TestCase):
raise KeyError raise KeyError
def __setitem__(self, key, value): def __setitem__(self, key, value):
self.results = (key, value) self.results = (key, value)
def keys(self): def __iter__(self):
return list('xyz') return iter('xyz')
m = M() m = M()
g = globals() g = globals()

View File

@ -38,7 +38,7 @@ class CookieTests(unittest.TestCase):
C.load(case['data']) C.load(case['data'])
self.assertEqual(repr(C), case['repr']) self.assertEqual(repr(C), case['repr'])
self.assertEqual(C.output(sep='\n'), case['output']) 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) self.assertEqual(C[k].value, v)
def test_load(self): def test_load(self):

View File

@ -491,7 +491,7 @@ class TestCopy(unittest.TestCase):
def test_reduce_5tuple(self): def test_reduce_5tuple(self):
class C(dict): class C(dict):
def __reduce__(self): def __reduce__(self):
return (C, (), self.__dict__, None, self.iteritems()) return (C, (), self.__dict__, None, self.items())
def __eq__(self, other): def __eq__(self, other):
return (dict(self) == dict(other) and return (dict(self) == dict(other) and
self.__dict__ == other.__dict__) self.__dict__ == other.__dict__)

View File

@ -183,7 +183,7 @@ def dict_constructor():
d = dict({1: 2, 'a': 'b'}) d = dict({1: 2, 'a': 'b'})
vereq(d, {1: 2, 'a': 'b'}) vereq(d, {1: 2, 'a': 'b'})
vereq(d, dict(d.items())) vereq(d, dict(d.items()))
vereq(d, dict(d.iteritems())) vereq(d, dict(d.items()))
d = dict({'one':1, 'two':2}) d = dict({'one':1, 'two':2})
vereq(d, dict(one=1, two=2)) vereq(d, dict(one=1, two=2))
vereq(d, dict(**d)) vereq(d, dict(**d))
@ -541,10 +541,10 @@ def spamdicts():
class C(spam.spamdict): class C(spam.spamdict):
def foo(self): return 1 def foo(self): return 1
a = C() a = C()
vereq(a.items(), []) vereq(list(a.items()), [])
vereq(a.foo(), 1) vereq(a.foo(), 1)
a['foo'] = 'bar' a['foo'] = 'bar'
vereq(a.items(), [('foo', 'bar')]) vereq(list(a.items()), [('foo', 'bar')])
vereq(a.getstate(), 0) vereq(a.getstate(), 0)
a.setstate(100) a.setstate(100)
vereq(a.getstate(), 100) vereq(a.getstate(), 100)
@ -714,7 +714,7 @@ def metaclass():
# named _get_x and/or _set_x are found # named _get_x and/or _set_x are found
def __new__(metaclass, name, bases, dict): def __new__(metaclass, name, bases, dict):
hits = {} hits = {}
for key, val in dict.iteritems(): for key, val in dict.items():
if key.startswith("_get_"): if key.startswith("_get_"):
key = key[5:] key = key[5:]
get, set = hits.get(key, (None, None)) get, set = hits.get(key, (None, None))
@ -725,7 +725,7 @@ def metaclass():
get, set = hits.get(key, (None, None)) get, set = hits.get(key, (None, None))
set = val set = val
hits[key] = get, set hits[key] = get, set
for key, (get, set) in hits.iteritems(): for key, (get, set) in hits.items():
dict[key] = property(get, set) dict[key] = property(get, set)
return super(autoproperty, metaclass).__new__(metaclass, return super(autoproperty, metaclass).__new__(metaclass,
name, bases, dict) name, bases, dict)
@ -820,9 +820,9 @@ def multi():
type({}).__init__(self) type({}).__init__(self)
C.__init__(self) C.__init__(self)
d = D() d = D()
vereq(d.keys(), []) vereq(list(d.keys()), [])
d["hello"] = "world" d["hello"] = "world"
vereq(d.items(), [("hello", "world")]) vereq(list(d.items()), [("hello", "world")])
vereq(d["hello"], "world") vereq(d["hello"], "world")
vereq(d.getstate(), 0) vereq(d.getstate(), 0)
d.setstate(10) d.setstate(10)
@ -2676,9 +2676,7 @@ def pickles():
cPickle = None cPickle = None
def sorteditems(d): def sorteditems(d):
L = d.items() return sorted(d.items())
L.sort()
return L
global C global C
class C(object): class C(object):
@ -3193,7 +3191,7 @@ def dictproxyiterkeys():
def meth(self): def meth(self):
pass pass
if verbose: print("Testing dict-proxy iterkeys...") 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() keys.sort()
vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth']) vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])
@ -3202,7 +3200,7 @@ def dictproxyitervalues():
def meth(self): def meth(self):
pass pass
if verbose: print("Testing dict-proxy itervalues...") 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) vereq(len(values), 5)
def dictproxyiteritems(): def dictproxyiteritems():
@ -3210,7 +3208,7 @@ def dictproxyiteritems():
def meth(self): def meth(self):
pass pass
if verbose: print("Testing dict-proxy iteritems...") 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() keys.sort()
vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth']) vereq(keys, ['__dict__', '__doc__', '__module__', '__weakref__', 'meth'])

View File

@ -4,19 +4,19 @@ from test import test_support
class DictSetTest(unittest.TestCase): class DictSetTest(unittest.TestCase):
def test_constructors_not_callable(self): def test_constructors_not_callable(self):
kt = type({}.KEYS()) kt = type({}.keys())
self.assertRaises(TypeError, kt, {}) self.assertRaises(TypeError, kt, {})
self.assertRaises(TypeError, kt) self.assertRaises(TypeError, kt)
it = type({}.ITEMS()) it = type({}.items())
self.assertRaises(TypeError, it, {}) self.assertRaises(TypeError, it, {})
self.assertRaises(TypeError, it) self.assertRaises(TypeError, it)
vt = type({}.VALUES()) vt = type({}.values())
self.assertRaises(TypeError, vt, {}) self.assertRaises(TypeError, vt, {})
self.assertRaises(TypeError, vt) self.assertRaises(TypeError, vt)
def test_dict_keys(self): def test_dict_keys(self):
d = {1: 10, "a": "ABC"} d = {1: 10, "a": "ABC"}
keys = d.KEYS() keys = d.keys()
self.assertEqual(set(keys), {1, "a"}) self.assertEqual(set(keys), {1, "a"})
self.assertEqual(len(keys), 2) self.assertEqual(len(keys), 2)
self.assert_(1 in keys) self.assert_(1 in keys)
@ -26,7 +26,7 @@ class DictSetTest(unittest.TestCase):
def test_dict_items(self): def test_dict_items(self):
d = {1: 10, "a": "ABC"} d = {1: 10, "a": "ABC"}
items = d.ITEMS() items = d.items()
self.assertEqual(set(items), {(1, 10), ("a", "ABC")}) self.assertEqual(set(items), {(1, 10), ("a", "ABC")})
self.assertEqual(len(items), 2) self.assertEqual(len(items), 2)
self.assert_((1, 10) in items) self.assert_((1, 10) in items)
@ -39,7 +39,7 @@ class DictSetTest(unittest.TestCase):
def test_dict_values(self): def test_dict_values(self):
d = {1: 10, "a": "ABC"} d = {1: 10, "a": "ABC"}
values = d.VALUES() values = d.values()
self.assertEqual(set(values), {10, "ABC"}) self.assertEqual(set(values), {10, "ABC"})
self.assertEqual(len(values), 2) self.assertEqual(len(values), 2)

View File

@ -365,8 +365,8 @@ class TestCase(unittest.TestCase):
d = {"one": 1, "two": 2, "three": 3} d = {"one": 1, "two": 2, "three": 3}
self.assertEqual(max(d), "two") self.assertEqual(max(d), "two")
self.assertEqual(min(d), "one") self.assertEqual(min(d), "one")
self.assertEqual(max(d.itervalues()), 3) self.assertEqual(max(d.values()), 3)
self.assertEqual(min(iter(d.itervalues())), 1) self.assertEqual(min(iter(d.values())), 1)
f = open(TESTFN, "w") f = open(TESTFN, "w")
try: try:
@ -402,7 +402,7 @@ class TestCase(unittest.TestCase):
for i in range(5)] for i in range(5)]
self.assertEqual(map(None, d, self.assertEqual(map(None, d,
SequenceClass(5), SequenceClass(5),
iter(d.iterkeys())), iter(d.keys())),
expected) expected)
f = open(TESTFN, "w") f = open(TESTFN, "w")
@ -437,7 +437,7 @@ class TestCase(unittest.TestCase):
[(0,), (1,), (2,)]) [(0,), (1,), (2,)])
d = {"one": 1, "two": 2, "three": 3} 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. # Generate all ints starting at constructor arg.
class IntsFrom: class IntsFrom:
@ -559,13 +559,13 @@ class TestCase(unittest.TestCase):
d = {"one": 1, "two": 2, "three": 3, 1j: 2j} d = {"one": 1, "two": 2, "three": 3, 1j: 2j}
for k in d: for k in d:
self.assert_(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(): for v in d.values():
self.assert_(v in d.itervalues()) self.assert_(v in d.values())
self.assert_(v not in d) self.assert_(v not in d)
for k, v in d.iteritems(): for k, v in d.items():
self.assert_((k, v) in d.iteritems()) self.assert_((k, v) in d.items())
self.assert_((v, k) not in d.iteritems()) self.assert_((v, k) not in d.items())
f = open(TESTFN, "w") f = open(TESTFN, "w")
try: try:
@ -600,9 +600,9 @@ class TestCase(unittest.TestCase):
d = {"one": 3, "two": 3, "three": 3, 1j: 2j} d = {"one": 3, "two": 3, "three": 3, 1j: 2j}
for k in d: for k in d:
self.assertEqual(countOf(d, k), 1) self.assertEqual(countOf(d, k), 1)
self.assertEqual(countOf(d.itervalues(), 3), 3) self.assertEqual(countOf(d.values(), 3), 3)
self.assertEqual(countOf(d.itervalues(), 2j), 1) self.assertEqual(countOf(d.values(), 2j), 1)
self.assertEqual(countOf(d.itervalues(), 1j), 0) self.assertEqual(countOf(d.values(), 1j), 0)
f = open(TESTFN, "w") f = open(TESTFN, "w")
try: try:
@ -744,7 +744,7 @@ class TestCase(unittest.TestCase):
else: else:
self.fail("should have raised TypeError") 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)) self.assertEqual((a, b, c), (42, 42, 42))
f = open(TESTFN, "w") f = open(TESTFN, "w")
@ -841,7 +841,7 @@ class TestCase(unittest.TestCase):
# XXX For a more thorough test, see towards the end of: # XXX For a more thorough test, see towards the end of:
# http://mail.python.org/pipermail/python-dev/2002-July/026512.html # http://mail.python.org/pipermail/python-dev/2002-July/026512.html
a = {1:1, 2:2, 0:0, 4:4, 3:3} 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) b = iter(a)
self.assertEqual(len(list(b)), 5) self.assertEqual(len(list(b)), 5)
self.assertEqual(list(b), []) self.assertEqual(list(b), [])

View File

@ -139,14 +139,14 @@ class TestDictItems(TestTemporarilyImmutable):
def setUp(self): def setUp(self):
d = dict.fromkeys(xrange(n)) d = dict.fromkeys(xrange(n))
self.it = d.iteritems() self.it = d.items()
self.mutate = d.popitem self.mutate = d.popitem
class TestDictValues(TestTemporarilyImmutable): class TestDictValues(TestTemporarilyImmutable):
def setUp(self): def setUp(self):
d = dict.fromkeys(xrange(n)) d = dict.fromkeys(xrange(n))
self.it = d.itervalues() self.it = d.values()
self.mutate = d.popitem self.mutate = d.popitem
class TestSet(TestTemporarilyImmutable): class TestSet(TestTemporarilyImmutable):

View File

@ -790,7 +790,7 @@ Samuele
>>> from operator import itemgetter >>> from operator import itemgetter
>>> d = dict(a=1, b=2, c=1, d=2, e=1, f=2, g=3) >>> 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)): >>> for k, g in groupby(di, itemgetter(1)):
... print(k, map(itemgetter(0), g)) ... print(k, map(itemgetter(0), g))
... ...
@ -823,7 +823,7 @@ Samuele
... return imap(function, count()) ... return imap(function, count())
>>> def iteritems(mapping): >>> def iteritems(mapping):
... return izip(mapping.iterkeys(), mapping.itervalues()) ... return izip(mapping.keys(), mapping.values())
>>> def nth(iterable, n): >>> def nth(iterable, n):
... "Returns the nth item" ... "Returns the nth item"

View File

@ -24,7 +24,7 @@ class TestBase(unittest.TestCase):
# Inspect a mailbox.Message representation of the sample message # Inspect a mailbox.Message representation of the sample message
self.assert_(isinstance(msg, email.message.Message)) self.assert_(isinstance(msg, email.message.Message))
self.assert_(isinstance(msg, mailbox.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_(value in msg.get_all(key))
self.assert_(msg.is_multipart()) self.assert_(msg.is_multipart())
self.assert_(len(msg.get_payload()) == len(_sample_payloads)) self.assert_(len(msg.get_payload()) == len(_sample_payloads))
@ -174,7 +174,7 @@ class TestMailbox(TestBase):
def test_iterkeys(self): def test_iterkeys(self):
# Get keys using iterkeys() # 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): def test_keys(self):
# Get keys using keys() # Get keys using keys()
@ -182,7 +182,7 @@ class TestMailbox(TestBase):
def test_itervalues(self): def test_itervalues(self):
# Get values using itervalues() # 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) do_values=True)
def test_iter(self): def test_iter(self):
@ -196,7 +196,7 @@ class TestMailbox(TestBase):
def test_iteritems(self): def test_iteritems(self):
# Get keys and values using iteritems() # 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) do_values=True)
def test_items(self): def test_items(self):
@ -424,12 +424,12 @@ class TestMailboxSuperclass(TestBase):
self.assertRaises(NotImplementedError, lambda: box.__delitem__('')) self.assertRaises(NotImplementedError, lambda: box.__delitem__(''))
self.assertRaises(NotImplementedError, lambda: box.discard('')) self.assertRaises(NotImplementedError, lambda: box.discard(''))
self.assertRaises(NotImplementedError, lambda: box.__setitem__('', '')) self.assertRaises(NotImplementedError, lambda: box.__setitem__('', ''))
self.assertRaises(NotImplementedError, lambda: box.iterkeys())
self.assertRaises(NotImplementedError, lambda: box.keys()) 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.__iter__().next())
self.assertRaises(NotImplementedError, lambda: box.values()) 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.items())
self.assertRaises(NotImplementedError, lambda: box.get('')) self.assertRaises(NotImplementedError, lambda: box.get(''))
self.assertRaises(NotImplementedError, lambda: box.__getitem__('')) self.assertRaises(NotImplementedError, lambda: box.__getitem__(''))
@ -709,7 +709,7 @@ class _TestMboxMMDF(TestMailbox):
mtime = os.path.getmtime(self._path) mtime = os.path.getmtime(self._path)
self._box = self._factory(self._path) self._box = self._factory(self._path)
self.assert_(len(self._box) == 3) 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.assert_(self._box.get_string(key) in values)
self._box.close() self._box.close()
self.assert_(mtime == os.path.getmtime(self._path)) self.assert_(mtime == os.path.getmtime(self._path))

View File

@ -46,7 +46,7 @@ def readFile(fname):
return r return r
def writeProfile(dict): 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)) writeFile(_mhprofile, "".join(contents))
def writeContext(folder): def writeContext(folder):
@ -61,7 +61,7 @@ def writeCurMessage(folder, cur):
def writeMessage(folder, n, headers, body): def writeMessage(folder, n, headers, body):
folder = normF(folder) 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) contents = "%s\n%s\n" % (headers,body)
mkdirs(os.path.join(_mhpath, folder)) mkdirs(os.path.join(_mhpath, folder))
writeFile(os.path.join(_mhpath, folder, str(n)), contents) writeFile(os.path.join(_mhpath, folder, str(n)), contents)

View File

@ -131,7 +131,7 @@ class VectorTest(unittest.TestCase):
self.checkequal("gt", a, b, [False, False, False, True, True ]) self.checkequal("gt", a, b, [False, False, False, True, True ])
self.checkequal("ge", a, b, [False, False, True, 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: for op in ops:
# calls __bool__, which should fail # calls __bool__, which should fail
self.assertRaises(TypeError, bool, op(a, b)) self.assertRaises(TypeError, bool, op(a, b))
@ -150,7 +150,7 @@ class NumberTest(unittest.TestCase):
continue # the combination int, int is useless continue # the combination int, int is useless
ta = typea(a) ta = typea(a)
tb = typeb(b) tb = typeb(b)
for ops in opmap.itervalues(): for ops in opmap.values():
for op in ops: for op in ops:
realoutcome = op(a, b) realoutcome = op(a, b)
testoutcome = op(ta, tb) testoutcome = op(ta, tb)

View File

@ -204,7 +204,7 @@ class ImportSideEffectTests(unittest.TestCase):
if sys.platform == "win32": if sys.platform == "win32":
import locale import locale
if locale.getdefaultlocale()[1].startswith('cp'): if locale.getdefaultlocale()[1].startswith('cp'):
for value in encodings.aliases.aliases.itervalues(): for value in encodings.aliases.aliases.values():
if value == "mbcs": if value == "mbcs":
break break
else: else:

View File

@ -239,8 +239,7 @@ def vereq(a, b):
def sortdict(dict): def sortdict(dict):
"Like repr(dict), but in sorted order." "Like repr(dict), but in sorted order."
items = dict.items() items = sorted(dict.items())
items.sort()
reprpairs = ["%r: %r" % pair for pair in items] reprpairs = ["%r: %r" % pair for pair in items]
withcommas = ", ".join(reprpairs) withcommas = ", ".join(reprpairs)
return "{%s}" % withcommas return "{%s}" % withcommas
@ -305,7 +304,7 @@ class EnvironmentVarGuard(object):
return self return self
def __exit__(self, *ignore_exc): def __exit__(self, *ignore_exc):
for envvar, value in self._reset.iteritems(): for envvar, value in self._reset.items():
self._environ[envvar] = value self._environ[envvar] = value
for unset in self._unset: for unset in self._unset:
del self._environ[unset] del self._environ[unset]

View File

@ -90,8 +90,7 @@ def test_request_headers_methods():
>>> r.header_items() >>> r.header_items()
[('Spam-eggs', 'blah')] [('Spam-eggs', 'blah')]
>>> r.add_header("Foo-Bar", "baz") >>> r.add_header("Foo-Bar", "baz")
>>> items = r.header_items() >>> items = sorted(r.header_items())
>>> items.sort()
>>> items >>> items
[('Foo-bar', 'baz'), ('Spam-eggs', 'blah')] [('Foo-bar', 'baz'), ('Spam-eggs', 'blah')]
@ -235,7 +234,7 @@ class MockFile:
class MockHeaders(dict): class MockHeaders(dict):
def getheaders(self, name): def getheaders(self, name):
return self.values() return list(self.values())
class MockResponse(StringIO.StringIO): class MockResponse(StringIO.StringIO):
def __init__(self, code, msg, headers, data, url=None): def __init__(self, code, msg, headers, data, url=None):

View File

@ -208,7 +208,7 @@ class SeqDict(UserDict.DictMixin):
if other is not None: if other is not None:
for (key, value) in other: for (key, value) in other:
self[key] = value self[key] = value
for (key, value) in kwargs.iteritems(): for (key, value) in kwargs.items():
self[key] = value self[key] = value
def __getitem__(self, key): def __getitem__(self, key):
try: try:
@ -234,7 +234,7 @@ class SeqDict(UserDict.DictMixin):
return list(self.keylist) return list(self.keylist)
def copy(self): def copy(self):
d = self.__class__() d = self.__class__()
for key, value in self.iteritems(): for key, value in self.items():
d[key] = value d[key] = value
return d return d
@classmethod @classmethod
@ -278,13 +278,13 @@ class UserDictMixinTest(mapping_tests.TestMappingProtocol):
self.assertEqual(len(s), 2) self.assertEqual(len(s), 2)
# iteritems # iteritems
self.assertEqual(list(s.iteritems()), [(10,'ten'), (30, 'thirty')]) self.assertEqual(list(s.items()), [(10,'ten'), (30, 'thirty')])
# iterkeys # iterkeys
self.assertEqual(list(s.iterkeys()), [10, 30]) self.assertEqual(list(s.keys()), [10, 30])
# itervalues # itervalues
self.assertEqual(list(s.itervalues()), ['ten', 'thirty']) self.assertEqual(list(s.values()), ['ten', 'thirty'])
# values # values
self.assertEqual(s.values(), ['ten', 'thirty']) self.assertEqual(s.values(), ['ten', 'thirty'])

View File

@ -295,7 +295,7 @@ class TestUUID(TestCase):
if TestUUID.last_node: if TestUUID.last_node:
if TestUUID.last_node != node: if TestUUID.last_node != node:
msg = "different sources disagree on node:\n" 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) msg += " from source %r, node was %012x\n" % (s, n)
# There's actually no reason to expect the MAC addresses # There's actually no reason to expect the MAC addresses
# to agree across various methods -- e.g., a box may have # to agree across various methods -- e.g., a box may have

View File

@ -839,7 +839,7 @@ class MappingTestCase(TestBase):
def check_iters(self, dict): def check_iters(self, dict):
# item iterator: # item iterator:
items = dict.items() items = dict.items()
for item in dict.iteritems(): for item in dict.items():
items.remove(item) items.remove(item)
self.assert_(len(items) == 0, "iteritems() did not touch all items") self.assert_(len(items) == 0, "iteritems() did not touch all items")
@ -851,13 +851,13 @@ class MappingTestCase(TestBase):
# key iterator, via iterkeys(): # key iterator, via iterkeys():
keys = dict.keys() keys = dict.keys()
for k in dict.iterkeys(): for k in dict.keys():
keys.remove(k) keys.remove(k)
self.assert_(len(keys) == 0, "iterkeys() did not touch all keys") self.assert_(len(keys) == 0, "iterkeys() did not touch all keys")
# value iterator: # value iterator:
values = dict.values() values = dict.values()
for v in dict.itervalues(): for v in dict.values():
values.remove(v) values.remove(v)
self.assert_(len(values) == 0, self.assert_(len(values) == 0,
"itervalues() did not touch all values") "itervalues() did not touch all values")
@ -1093,7 +1093,7 @@ None
... def __init__(self, ob, callback=None, **annotations): ... def __init__(self, ob, callback=None, **annotations):
... super(ExtendedRef, self).__init__(ob, callback) ... super(ExtendedRef, self).__init__(ob, callback)
... self.__counter = 0 ... self.__counter = 0
... for k, v in annotations.iteritems(): ... for k, v in annotations.items():
... setattr(self, k, v) ... setattr(self, k, v)
... def __call__(self): ... def __call__(self):
... '''Return a pair containing the referent and the number of ... '''Return a pair containing the referent and the number of
@ -1104,7 +1104,7 @@ None
... self.__counter += 1 ... self.__counter += 1
... ob = (ob, self.__counter) ... ob = (ob, self.__counter)
... return ob ... return ob
... ...
>>> class A: # not in docs from here, just testing the ExtendedRef >>> class A: # not in docs from here, just testing the ExtendedRef
... pass ... pass
... ...

View File

@ -145,7 +145,7 @@ class XMLRPCTestCase(unittest.TestCase):
if not setdefaultencoding_existed: if not setdefaultencoding_existed:
del sys.setdefaultencoding del sys.setdefaultencoding
items = d.items() items = list(d.items())
if have_unicode: if have_unicode:
self.assertEquals(s, u"abc \x95") self.assertEquals(s, u"abc \x95")
self.assert_(isinstance(s, unicode)) self.assert_(isinstance(s, unicode))

View File

@ -707,7 +707,7 @@ def activeCount():
def enumerate(): def enumerate():
_active_limbo_lock.acquire() _active_limbo_lock.acquire()
active = _active.values() + _limbo.values() active = list(_active.values()) + list(_limbo.values())
_active_limbo_lock.release() _active_limbo_lock.release()
return active return active

View File

@ -68,7 +68,7 @@ NT_OFFSET = 256
#--end constants-- #--end constants--
tok_name = {} tok_name = {}
for _name, _value in globals().items(): for _name, _value in list(globals().items()):
if type(_value) is type(0): if type(_value) is type(0):
tok_name[_value] = _name tok_name[_value] = _name

View File

@ -282,7 +282,7 @@ class CoverageResults:
# accumulate summary info, if needed # accumulate summary info, if needed
sums = {} sums = {}
for filename, count in per_file.iteritems(): for filename, count in per_file.items():
# skip some "files" we don't care about... # skip some "files" we don't care about...
if filename == "<string>": if filename == "<string>":
continue continue

View File

@ -281,7 +281,7 @@ class Request:
def header_items(self): def header_items(self):
hdrs = self.unredirected_hdrs.copy() hdrs = self.unredirected_hdrs.copy()
hdrs.update(self.headers) hdrs.update(self.headers)
return hdrs.items() return list(hdrs.items())
class OpenerDirector: class OpenerDirector:
def __init__(self): def __init__(self):
@ -710,7 +710,7 @@ class HTTPPasswordMgr:
domains = self.passwd.get(realm, {}) domains = self.passwd.get(realm, {})
for default_port in True, False: for default_port in True, False:
reduced_authuri = self.reduce_uri(authuri, default_port) reduced_authuri = self.reduce_uri(authuri, default_port)
for uris, authinfo in domains.iteritems(): for uris, authinfo in domains.items():
for uri in uris: for uri in uris:
if self.is_suburi(uri, reduced_authuri): if self.is_suburi(uri, reduced_authuri):
return authinfo return authinfo
@ -1318,21 +1318,21 @@ class CacheFTPHandler(FTPHandler):
# first check for old ones # first check for old ones
t = time.time() t = time.time()
if self.soonest <= t: if self.soonest <= t:
for k, v in self.timeout.items(): for k, v in list(self.timeout.items()):
if v < t: if v < t:
self.cache[k].close() self.cache[k].close()
del self.cache[k] del self.cache[k]
del self.timeout[k] del self.timeout[k]
self.soonest = min(self.timeout.values()) self.soonest = min(list(self.timeout.values()))
# then check the size # then check the size
if len(self.cache) == self.max_conns: 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: if v == self.soonest:
del self.cache[k] del self.cache[k]
del self.timeout[k] del self.timeout[k]
break break
self.soonest = min(self.timeout.values()) self.soonest = min(list(self.timeout.values()))
class GopherHandler(BaseHandler): class GopherHandler(BaseHandler):
def gopher_open(self, req): def gopher_open(self, req):

View File

@ -100,16 +100,16 @@ class WeakValueDictionary(UserDict.UserDict):
return L return L
def iteritems(self): def iteritems(self):
for wr in self.data.itervalues(): for wr in self.data.values():
value = wr() value = wr()
if value is not None: if value is not None:
yield wr.key, value yield wr.key, value
def iterkeys(self): def iterkeys(self):
return self.data.iterkeys() return self.data.keys()
def __iter__(self): def __iter__(self):
return self.data.iterkeys() return self.data.keys()
def itervaluerefs(self): def itervaluerefs(self):
"""Return an iterator that yields the weak references to the values. """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. keep the values around longer than needed.
""" """
return self.data.itervalues() return self.data.values()
def itervalues(self): def itervalues(self):
for wr in self.data.itervalues(): for wr in self.data.values():
obj = wr() obj = wr()
if obj is not None: if obj is not None:
yield obj yield obj
@ -268,7 +268,7 @@ class WeakKeyDictionary(UserDict.UserDict):
return L return L
def iteritems(self): def iteritems(self):
for wr, value in self.data.iteritems(): for wr, value in self.data.items():
key = wr() key = wr()
if key is not None: if key is not None:
yield key, value yield key, value
@ -283,19 +283,19 @@ class WeakKeyDictionary(UserDict.UserDict):
keep the keys around longer than needed. keep the keys around longer than needed.
""" """
return self.data.iterkeys() return self.data.keys()
def iterkeys(self): def iterkeys(self):
for wr in self.data.iterkeys(): for wr in self.data.keys():
obj = wr() obj = wr()
if obj is not None: if obj is not None:
yield obj yield obj
def __iter__(self): def __iter__(self):
return self.iterkeys() return self.keys()
def itervalues(self): def itervalues(self):
return self.data.itervalues() return self.data.values()
def keyrefs(self): def keyrefs(self):
"""Return a list of weak references to the keys. """Return a list of weak references to the keys.

View File

@ -645,7 +645,7 @@ class ElementTree:
elif tag is ProcessingInstruction: elif tag is ProcessingInstruction:
file.write("<?%s?>" % _escape_cdata(node.text, encoding)) file.write("<?%s?>" % _escape_cdata(node.text, encoding))
else: else:
items = node.items() items = list(node.items())
xmlns_items = [] # new namespaces in this scope xmlns_items = [] # new namespaces in this scope
try: try:
if isinstance(tag, QName) or tag[:1] == "{": if isinstance(tag, QName) or tag[:1] == "{":

View File

@ -36,6 +36,9 @@ TO DO
Core and Builtins 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 - 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 '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 it). A side effect of this change is that you can get incomplete

View File

@ -1752,7 +1752,7 @@ save_dict(Picklerobject *self, PyObject *args)
int res = -1; int res = -1;
char s[3]; char s[3];
int len; int len;
PyObject *iter; PyObject *items, *iter;
if (self->fast && !fast_save_enter(self, args)) if (self->fast && !fast_save_enter(self, args))
goto finally; goto finally;
@ -1784,7 +1784,11 @@ save_dict(Picklerobject *self, PyObject *args)
goto finally; goto finally;
/* Materialize the dict items. */ /* 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) if (iter == NULL)
goto finally; goto finally;
res = batch_dict(self, iter); res = batch_dict(self, iter);

View File

@ -1140,6 +1140,7 @@ defdict_reduce(defdictobject *dd)
*/ */
PyObject *args; PyObject *args;
PyObject *items; PyObject *items;
PyObject *iteritems;
PyObject *result; PyObject *result;
if (dd->default_factory == NULL || dd->default_factory == Py_None) if (dd->default_factory == NULL || dd->default_factory == Py_None)
args = PyTuple_New(0); args = PyTuple_New(0);
@ -1147,14 +1148,20 @@ defdict_reduce(defdictobject *dd)
args = PyTuple_Pack(1, dd->default_factory); args = PyTuple_Pack(1, dd->default_factory);
if (args == NULL) if (args == NULL)
return NULL; return NULL;
items = PyObject_CallMethod((PyObject *)dd, "iteritems", "()"); items = PyObject_CallMethod((PyObject *)dd, "items", "()");
if (items == NULL) { if (items == NULL) {
Py_DECREF(args); Py_DECREF(args);
return NULL; return NULL;
} }
result = PyTuple_Pack(5, dd->dict.ob_type, args, iteritems = PyObject_GetIter(items);
Py_None, Py_None, items);
Py_DECREF(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); Py_DECREF(args);
return result; return result;
} }

View File

@ -1657,6 +1657,54 @@ PyMapping_HasKey(PyObject *o, PyObject *key)
return 0; 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 */ /* Operations on callable objects */
/* XXX PyCallable_Check() is in object.c */ /* XXX PyCallable_Check() is in object.c */

View File

@ -1760,6 +1760,7 @@ extern PyTypeObject PyDictIterValue_Type; /* Forward */
extern PyTypeObject PyDictIterItem_Type; /* Forward */ extern PyTypeObject PyDictIterItem_Type; /* Forward */
static PyObject *dictiter_new(dictobject *, PyTypeObject *); static PyObject *dictiter_new(dictobject *, PyTypeObject *);
#if 0
static PyObject * static PyObject *
dict_iterkeys(dictobject *dict) dict_iterkeys(dictobject *dict)
{ {
@ -1777,6 +1778,7 @@ dict_iteritems(dictobject *dict)
{ {
return dictiter_new(dict, &PyDictIterItem_Type); return dictiter_new(dict, &PyDictIterItem_Type);
} }
#endif
PyDoc_STRVAR(contains__doc__, 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\ "D.popitem() -> (k, v), remove and return some (key, value) pair as a\n\
2-tuple; but raise KeyError if D is empty"); 2-tuple; but raise KeyError if D is empty");
#if 0
PyDoc_STRVAR(keys__doc__, PyDoc_STRVAR(keys__doc__,
"D.keys() -> list of D's keys"); "D.keys() -> list of D's keys");
@ -1806,6 +1809,7 @@ PyDoc_STRVAR(items__doc__,
PyDoc_STRVAR(values__doc__, PyDoc_STRVAR(values__doc__,
"D.values() -> list of D's values"); "D.values() -> list of D's values");
#endif
PyDoc_STRVAR(update__doc__, PyDoc_STRVAR(update__doc__,
"D.update(E, **F) -> None. Update D from E and F: for k in E: D[k] = E[k]\ "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__, PyDoc_STRVAR(copy__doc__,
"D.copy() -> a shallow copy of D"); "D.copy() -> a shallow copy of D");
#if 0
PyDoc_STRVAR(iterkeys__doc__, PyDoc_STRVAR(iterkeys__doc__,
"D.iterkeys() -> an iterator over the keys of D"); "D.iterkeys() -> an iterator over the keys of D");
@ -1829,6 +1834,7 @@ PyDoc_STRVAR(itervalues__doc__,
PyDoc_STRVAR(iteritems__doc__, PyDoc_STRVAR(iteritems__doc__,
"D.iteritems() -> an iterator over the (key, value) items of D"); "D.iteritems() -> an iterator over the (key, value) items of D");
#endif
/* Forward */ /* Forward */
static PyObject *dictkeys_new(PyObject *); static PyObject *dictkeys_new(PyObject *);
@ -1852,18 +1858,20 @@ static PyMethodDef mapp_methods[] = {
pop__doc__}, pop__doc__},
{"popitem", (PyCFunction)dict_popitem, METH_NOARGS, {"popitem", (PyCFunction)dict_popitem, METH_NOARGS,
popitem__doc__}, popitem__doc__},
#if 0
{"keys", (PyCFunction)dict_keys, METH_NOARGS, {"keys", (PyCFunction)dict_keys, METH_NOARGS,
keys__doc__}, 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", (PyCFunction)dict_items, METH_NOARGS,
items__doc__}, items__doc__},
{"values", (PyCFunction)dict_values, METH_NOARGS, {"values", (PyCFunction)dict_values, METH_NOARGS,
values__doc__}, 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", (PyCFunction)dict_update, METH_VARARGS | METH_KEYWORDS,
update__doc__}, update__doc__},
{"fromkeys", (PyCFunction)dict_fromkeys, METH_VARARGS | METH_CLASS, {"fromkeys", (PyCFunction)dict_fromkeys, METH_VARARGS | METH_CLASS,
@ -1872,12 +1880,14 @@ static PyMethodDef mapp_methods[] = {
clear__doc__}, clear__doc__},
{"copy", (PyCFunction)dict_copy, METH_NOARGS, {"copy", (PyCFunction)dict_copy, METH_NOARGS,
copy__doc__}, copy__doc__},
#if 0
{"iterkeys", (PyCFunction)dict_iterkeys, METH_NOARGS, {"iterkeys", (PyCFunction)dict_iterkeys, METH_NOARGS,
iterkeys__doc__}, iterkeys__doc__},
{"itervalues", (PyCFunction)dict_itervalues, METH_NOARGS, {"itervalues", (PyCFunction)dict_itervalues, METH_NOARGS,
itervalues__doc__}, itervalues__doc__},
{"iteritems", (PyCFunction)dict_iteritems, METH_NOARGS, {"iteritems", (PyCFunction)dict_iteritems, METH_NOARGS,
iteritems__doc__}, iteritems__doc__},
#endif
{NULL, NULL} /* sentinel */ {NULL, NULL} /* sentinel */
}; };

View File

@ -2601,7 +2601,11 @@ reduce_2(PyObject *obj)
Py_INCREF(dictitems); Py_INCREF(dictitems);
} }
else { 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) if (dictitems == NULL)
goto end; goto end;
} }