Skip to content

Commit

Permalink
- PEP 3106: dict.iterkeys(), .iteritems(), .itervalues() are now gone;
Browse files Browse the repository at this point in the history
  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.
  • Loading branch information
gvanrossum committed Feb 11, 2007
1 parent 4e66dfc commit cc2b016
Show file tree
Hide file tree
Showing 73 changed files with 317 additions and 272 deletions.
35 changes: 13 additions & 22 deletions Include/abstract.h
Original file line number Diff line number Diff line change
Expand Up @@ -1127,37 +1127,28 @@ xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx*/
*/

/* Implemented as macro:
PyAPI_FUNC(PyObject *) PyMapping_Keys(PyObject *o);

PyObject *PyMapping_Keys(PyObject *o);
On success, return a list of the keys in object o. On
failure, return NULL. This is equivalent to the Python
expression: o.keys().
/*
On success, return a list or tuple of the keys in object o.
On failure, return NULL.
*/
#define PyMapping_Keys(O) PyObject_CallMethod(O,"keys",NULL)

/* Implemented as macro:

PyObject *PyMapping_Values(PyObject *o);
PyAPI_FUNC(PyObject *) PyMapping_Values(PyObject *o);

On success, return a list of the values in object o. On
failure, return NULL. This is equivalent to the Python
expression: o.values().
/*
On success, return a list or tuple of the values in object o.
On failure, return NULL.
*/
#define PyMapping_Values(O) PyObject_CallMethod(O,"values",NULL)

/* Implemented as macro:

PyObject *PyMapping_Items(PyObject *o);
PyAPI_FUNC(PyObject *) PyMapping_Items(PyObject *o);

On success, return a list of the items in object o, where
each item is a tuple containing a key-value pair. On
failure, return NULL. This is equivalent to the Python
expression: o.items().
/*
On success, return a list or tuple of the items in object o,
where each item is a tuple containing a key-value pair.
On failure, return NULL.
*/
#define PyMapping_Items(O) PyObject_CallMethod(O,"items",NULL)

PyAPI_FUNC(PyObject *) PyMapping_GetItemString(PyObject *o, char *key);

Expand Down
6 changes: 3 additions & 3 deletions Lib/ConfigParser.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ def defaults(self):
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.
Expand Down Expand Up @@ -242,7 +242,7 @@ def options(self, section):
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.
Expand Down Expand Up @@ -547,7 +547,7 @@ def items(self, section, raw=False, vars=None):
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:
Expand Down
12 changes: 4 additions & 8 deletions Lib/Cookie.py
Original file line number Diff line number Diff line change
Expand Up @@ -488,8 +488,7 @@ def OutputString(self, attrs=None):
# 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
Expand Down Expand Up @@ -582,8 +581,7 @@ def __setitem__(self, key, value):
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)
Expand All @@ -593,17 +591,15 @@ def output(self, attrs=None, header="Set-Cookie:", sep="\015\012"):

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

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)
Expand Down
27 changes: 15 additions & 12 deletions Lib/UserDict.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,9 @@ def copy(self):
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:
Expand Down Expand Up @@ -111,12 +111,12 @@ def iterkeys(self):

# 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]
Expand All @@ -140,7 +140,7 @@ def pop(self, key, *args):
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]
Expand All @@ -152,6 +152,9 @@ def update(self, other=None, **kwargs):
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]
Expand All @@ -166,14 +169,14 @@ def get(self, key, default=None):
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())
3 changes: 1 addition & 2 deletions Lib/_LWPCookieJar.py
Original file line number Diff line number Diff line change
Expand Up @@ -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])))

Expand Down
2 changes: 1 addition & 1 deletion Lib/_strptime.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 1 addition & 2 deletions Lib/_threading_local.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,8 +28,7 @@
>>> log = []
>>> def f():
... items = mydata.__dict__.items()
... items.sort()
... items = sorted(mydata.__dict__.items())
... log.append(items)
... mydata.number = 11
... log.append(mydata.number)
Expand Down
4 changes: 1 addition & 3 deletions Lib/base64.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,9 +126,7 @@ def urlsafe_b64decode(s):
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()])


Expand Down
2 changes: 1 addition & 1 deletion Lib/compiler/ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -1337,6 +1337,6 @@ def getChildNodes(self):
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
2 changes: 1 addition & 1 deletion Lib/compiler/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def __contains__(self, elt):
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):
Expand Down
4 changes: 2 additions & 2 deletions Lib/compiler/pyassem.py
Original file line number Diff line number Diff line change
Expand Up @@ -504,7 +504,7 @@ def sort_cellvars(self):
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):
Expand Down Expand Up @@ -573,7 +573,7 @@ def _convert_COMPARE_OP(self, arg):

# 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
Expand Down
3 changes: 1 addition & 2 deletions Lib/cookielib.py
Original file line number Diff line number Diff line change
Expand Up @@ -1171,8 +1171,7 @@ def path_return_ok(self, path, request):


def vals_sorted_by_key(adict):
keys = adict.keys()
keys.sort()
keys = sorted(adict.keys())
return map(adict.get, keys)

def deepvalues(mapping):
Expand Down
6 changes: 3 additions & 3 deletions Lib/copy.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ def _deepcopy_tuple(x, memo):
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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -337,7 +337,7 @@ def __init__(self, arg=None):
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))
Expand Down
6 changes: 3 additions & 3 deletions Lib/csv.py
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ def _guess_delimiter(self, data, delimiters):
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
Expand Down Expand Up @@ -308,7 +308,7 @@ def _guess_delimiter(self, data, delimiters):
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)
Expand Down Expand Up @@ -367,7 +367,7 @@ def has_header(self, sample):
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:
Expand Down
2 changes: 1 addition & 1 deletion Lib/ctypes/test/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion Lib/difflib.py
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ def __chain_b(self):
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]
Expand Down
2 changes: 1 addition & 1 deletion Lib/distutils/sysconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
4 changes: 2 additions & 2 deletions Lib/dumbdbm.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ def _commit(self):

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

Expand Down Expand Up @@ -202,7 +202,7 @@ def __contains__(self, key):
return key in self._index

def iterkeys(self):
return self._index.iterkeys()
return self._index.keys()
__iter__ = iterkeys

def __len__(self):
Expand Down
3 changes: 1 addition & 2 deletions Lib/encodings/punycode.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
Loading

0 comments on commit cc2b016

Please sign in to comment.