- 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 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:
PyAPI_FUNC(PyObject *) PyMapping_Values(PyObject *o);
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:
PyAPI_FUNC(PyObject *) PyMapping_Items(PyObject *o);
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);

View File

@ -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:

View File

@ -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)

View File

@ -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())

View File

@ -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])))

View File

@ -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

View File

@ -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)

View File

@ -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()])

View File

@ -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

View File

@ -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):

View File

@ -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

View File

@ -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):

View File

@ -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))

View File

@ -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:

View File

@ -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:

View File

@ -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]

View File

@ -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:

View File

@ -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):

View File

@ -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):

View File

@ -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()

View File

@ -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)

View File

@ -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()

View File

@ -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:

View File

@ -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:

View File

@ -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')

View File

@ -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:

View File

@ -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

View File

@ -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):

View File

@ -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)

View File

@ -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)

View File

@ -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 = {}

View File

@ -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

View File

@ -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)

View File

@ -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()

View File

@ -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:

View File

@ -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):

View File

@ -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

View File

@ -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

View File

@ -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)

View File

@ -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):

View File

@ -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(

View File

@ -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())

View File

@ -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)

View File

@ -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()

View File

@ -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):

View File

@ -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__)

View File

@ -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'])

View File

@ -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)

View File

@ -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), [])

View File

@ -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):

View File

@ -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"

View File

@ -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))

View File

@ -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)

View File

@ -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)

View File

@ -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:

View File

@ -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]

View File

@ -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):

View File

@ -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'])

View File

@ -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

View File

@ -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
...

View File

@ -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))

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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):

View File

@ -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.

View File

@ -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] == "{":

View File

@ -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

View File

@ -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);

View File

@ -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;
}

View File

@ -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 */

View File

@ -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 */
};

View File

@ -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;
}