Remove use of fix_dict fixer.

This commit is contained in:
Valentin Lorentz 2015-08-08 22:20:14 +02:00
parent 70fb09b489
commit be118c3338
41 changed files with 121 additions and 116 deletions

View File

@ -695,7 +695,8 @@ class Aka(callbacks.Plugin):
if alias_plugin is None:
irc.error(_('Alias plugin is not loaded.'), Raise=True)
errors = {}
for (name, (command, locked, func)) in alias_plugin.aliases.items():
for (name, (command, locked, func)) in \
list(alias_plugin.aliases.items()):
try:
self._add_aka('global', name, command)
except AkaError as e:

View File

@ -241,7 +241,7 @@ class Alias(callbacks.Plugin):
# XXX This should go. aliases should be a space separate list, etc.
group = conf.supybot.plugins.Alias.aliases
group2 = conf.supybot.plugins.Alias.escapedaliases
for (name, alias) in registry._cache.iteritems():
for (name, alias) in registry._cache.items():
name = name.lower()
if name.startswith('supybot.plugins.alias.aliases.'):
name = name[len('supybot.plugins.alias.aliases.'):]

View File

@ -549,7 +549,7 @@ class Channel(callbacks.Plugin):
Returns the channels in which this bot is lobotomized.
"""
L = []
for (channel, c) in ircdb.channels.iteritems():
for (channel, c) in ircdb.channels.items():
if c.lobotomized:
chancap = ircdb.makeChannelCapability(channel, 'op')
if ircdb.checkCapability(msg.prefix, 'admin') or \

View File

@ -93,8 +93,8 @@ class ChannelLogger(callbacks.Plugin):
self.lastStates.clear()
def _logs(self):
for logs in self.logs.itervalues():
for log in logs.itervalues():
for logs in self.logs.values():
for log in logs.values():
yield log
def flush(self):

View File

@ -222,7 +222,7 @@ class ChannelStats(callbacks.Plugin):
id = ircdb.users.getUserId(msg.prefix)
except KeyError:
id = None
for (channel, c) in self.laststate.channels.iteritems():
for (channel, c) in self.laststate.channels.items():
if msg.nick in c.users:
if (channel, 'channelStats') not in self.db:
self.db[channel, 'channelStats'] = ChannelStat()

View File

@ -121,7 +121,7 @@ class Config(callbacks.Plugin):
def _list(self, group):
L = []
for (vname, v) in group._children.iteritems():
for (vname, v) in group._children.items():
if hasattr(group, 'channelValue') and group.channelValue and \
ircutils.isChannel(vname) and not v._children:
continue

View File

@ -143,7 +143,7 @@ class Ctcp(callbacks.PluginRegexp):
def doReply():
if self.versions:
L = []
for (reply, nickslist) in self.versions.iteritems():
for (reply, nickslist) in self.versions.items():
if nicks:
L.append(format('%L responded with %q', nickslist, reply))
else:

View File

@ -358,9 +358,9 @@ class Factoids(callbacks.Plugin, plugins.ChannelDBHandler):
dl_metrics = [dameraulevenshtein(key, sourcekey) for sourcekey in flkeys]
dict_metrics = dict(list(zip(flkeys, dl_metrics)))
if min(dl_metrics) <= 2:
return [key for key,item in dict_metrics.iteritems() if item <= 2]
return [key for key,item in dict_metrics.items() if item <= 2]
if min(dl_metrics) <= 3:
return [key for key,item in dict_metrics.iteritems() if item <= 3]
return [key for key,item in dict_metrics.items() if item <= 3]
return []

View File

@ -147,7 +147,6 @@ class Filter(callbacks.Plugin):
"""
L = []
if sys.version_info[0] >= 3:
print(repr(text))
if isinstance(text, str):
bytes_ = text.encode()
else:
@ -509,7 +508,7 @@ class Filter(callbacks.Plugin):
r'\blike\b': 'liek',
r'[^e]ing\b': 'eing',
}
for (r, s) in alwaysInsertions.iteritems():
for (r, s) in alwaysInsertions.items():
text = re.sub(r, s, text)
randomInsertions = {
r'i': 'ui',
@ -527,7 +526,7 @@ class Filter(callbacks.Plugin):
r'\btheir\b': 'there',
r'[^e]y': 'ey',
}
for (r, s) in randomInsertions.iteritems():
for (r, s) in randomInsertions.items():
text = re.sub(r, randomlyReplace(s), text)
text = re.sub(r'(\w)\'(\w)', quoteOrNothing, text)
text = re.sub(r'\.(\s+|$)', randomExclaims, text)
@ -551,7 +550,7 @@ class Filter(callbacks.Plugin):
'v': _('vee'), 'w': _('double-you'), 'x': _('ecks'), 'y': _('why'),
'z': _('zee')
}
for (k, v) in _spellLetters.items():
for (k, v) in list(_spellLetters.items()):
_spellLetters[k.upper()] = v
_spellPunctuation = {
'!': _('exclamation point'),
@ -607,7 +606,7 @@ class Filter(callbacks.Plugin):
d.update(self._spellPunctuation)
# A bug in unicode on OSX prevents me from testing this.
## dd = {}
## for (c, v) in d.iteritems():
## for (c, v) in d.items():
## dd[ord(c)] = unicode(v + ' ')
## irc.reply(unicode(text).translate(dd))
out = StringIO()

View File

@ -100,7 +100,7 @@ class GPGTestCase(PluginTestCase):
def testGpgAuth(self):
self.assertNotError('register spam egg')
gpg.keyring.import_keys(PRIVATE_KEY).__dict__
(id, user) = ircdb.users.items()[0]
(id, user) = list(ircdb.users.items())[0]
user.gpgkeys.append(FINGERPRINT)
msg = self.getMsg('gpg signing gettoken').args[-1]
match = re.search('is: ({.*}).', msg)

View File

@ -99,7 +99,7 @@ class Google(callbacks.PluginRegexp):
headers = dict(utils.web.defaultHeaders)
headers['Referer'] = ref
opts = {'q': query, 'v': '1.0'}
for (k, v) in options.iteritems():
for (k, v) in options.items():
if k == 'smallsearch':
if v:
opts['rsz'] = 'small'

View File

@ -50,7 +50,7 @@ class SqliteKarmaDB(object):
self.filename = filename
def close(self):
for db in self.dbs.itervalues():
for db in self.dbs.values():
db.close()
def _getDb(self, channel):
@ -100,11 +100,11 @@ class SqliteKarmaDB(object):
criteria = ' OR '.join(['normalized=?'] * len(normalizedThings))
sql = """SELECT name, added-subtracted FROM karma
WHERE %s ORDER BY added-subtracted DESC""" % criteria
cursor.execute(sql, normalizedThings.keys())
cursor.execute(sql, list(normalizedThings.keys()))
L = [(name, int(karma)) for (name, karma) in cursor.fetchall()]
for (name, _) in L:
del normalizedThings[name.lower()]
neutrals = normalizedThings.values()
neutrals = list(normalizedThings.values())
neutrals.sort()
return (L, neutrals)

View File

@ -61,7 +61,7 @@ class Later(callbacks.Plugin):
def _flushNotes(self):
fd = utils.file.AtomicFile(self.filename)
writer = csv.writer(fd)
for (nick, notes) in self._notes.iteritems():
for (nick, notes) in self._notes.items():
for (time, whence, text) in notes:
writer.writerow([nick, time, whence, text])
fd.close()
@ -125,7 +125,7 @@ class Later(callbacks.Plugin):
expiry = self.registryValue('messageExpiry')
curtime = time.time()
nickremovals=[]
for (nick, notes) in self._notes.iteritems():
for (nick, notes) in self._notes.items():
removals = []
for (notetime, whence, text) in notes:
td = datetime.timedelta(seconds=(curtime - notetime))

View File

@ -1083,7 +1083,7 @@ class UnitData(dict):
for unit in units:
self[unit.name.replace(' ', '')] = unit
typeUnits[unit.typeName].append(unit.name)
self.sortedKeys = self.keys()
self.sortedKeys = list(self.keys())
self.sortedKeys.sort()
if len(self.sortedKeys) < len(units):

View File

@ -270,7 +270,7 @@ class Misc(callbacks.Plugin):
for command in cb.listCommands():
if s in command:
commands.setdefault(command, []).append(cb.name())
for (key, names) in commands.iteritems():
for (key, names) in commands.items():
for name in names:
L.append('%s %s' % (name, key))
if L:
@ -473,7 +473,7 @@ class Misc(callbacks.Plugin):
# Drop the first message only if our current channel is the same as
# the channel we've been instructed to look at.
next(iterable)
predicates = list(utils.iter.flatten(predicates.itervalues()))
predicates = list(utils.iter.flatten(predicates.values()))
# Make sure the user can't get messages from channels they aren't in
def userInChannel(m):
return m.args[0] in irc.state.channels \

View File

@ -94,7 +94,7 @@ class SqliteMoobotDB(object):
self.dbs = ircutils.IrcDict()
def close(self):
for db in self.dbs.itervalues():
for db in self.dbs.values():
db.close()
self.dbs.clear()

View File

@ -397,7 +397,7 @@ class Note(callbacks.Plugin):
else:
temp[note[1]] = [note[0]]
notes = []
for (k,v) in temp.iteritems():
for (k,v) in temp.items():
if '(private)' in k:
k = k.replace('(private)', format('%b private', len(v)))
notes.append(format('%L %s', v, k))

View File

@ -96,7 +96,7 @@ class Owner(callbacks.Plugin):
# This needs to be done before we connect to any networks so that the
# children of supybot.plugins (the actual plugins) exist and can be
# loaded.
for (name, s) in registry._cache.iteritems():
for (name, s) in registry._cache.items():
if 'alwaysLoadDefault' in name or 'alwaysLoadImportant' in name:
continue
if name.startswith('supybot.plugins'):

View File

@ -162,7 +162,7 @@ class Plugin(callbacks.Plugin):
Sort the list of 'long names' based on the number of contributions
associated with each.
"""
L = module.__contributors__.items()
L = list(module.__contributors__.items())
def negativeSecondElement(x):
return -len(x[1])
utils.sortBy(negativeSecondElement, L)

View File

@ -73,7 +73,7 @@ class SqliteQuoteGrabsDB(object):
self.filename = filename
def close(self):
for db in self.dbs.itervalues():
for db in self.dbs.values():
db.close()
def _getDb(self, channel):

View File

@ -67,7 +67,7 @@ class Scheduler(callbacks.Plugin):
except IOError as e:
self.log.debug('Unable to open pickle file: %s', e)
return
for name, event in eventdict.iteritems():
for name, event in eventdict.items():
ircobj = callbacks.ReplyIrcProxy(irc, event['msg'])
try:
if event['type'] == 'single': # non-repeating event
@ -197,7 +197,7 @@ class Scheduler(callbacks.Plugin):
Lists the currently scheduled events.
"""
L = self.events.items()
L = list(self.events.items())
if L:
L.sort()
for (i, (name, command)) in enumerate(L):

View File

@ -46,7 +46,7 @@ class ShrinkUrlTestCase(ChannelPluginTestCase):
}
if network:
def testShrink(self):
for (service, testdata) in self.tests.iteritems():
for (service, testdata) in self.tests.items():
for (url, shrunkurl) in testdata:
self.assertRegexp('shrinkurl %s %s' % (service, url),
shrunkurl)

View File

@ -69,7 +69,7 @@ class FlatTodoDb(object):
return self.dbs[uid]
def close(self):
for db in self.dbs.itervalues():
for db in self.dbs.values():
db.close()
def get(self, uid, tid):

View File

@ -80,7 +80,7 @@ class User(callbacks.Plugin):
return r.match(u.name) is not None
predicates.append(p)
users = []
for u in ircdb.users.itervalues():
for u in ircdb.users.values():
for predicate in predicates:
if not predicate(u):
break
@ -492,7 +492,7 @@ class User(callbacks.Plugin):
owners = 0
admins = 0
hostmasks = 0
for user in ircdb.users.itervalues():
for user in ircdb.users.values():
users += 1
hostmasks += len(user.hostmasks)
try:

View File

@ -128,7 +128,7 @@ class ChannelDBHandler(object):
return db
def die(self):
for db in self.dbCache.itervalues():
for db in self.dbCache.values():
try:
db.commit()
except AttributeError: # In case it's not an SQLite database.
@ -158,11 +158,11 @@ class DbiChannelDB(object):
return db
def close(self):
for db in self.dbs.itervalues():
for db in self.dbs.values():
db.close()
def flush(self):
for db in self.dbs.itervalues():
for db in self.dbs.values():
db.flush()
def __getattr__(self, attr):
@ -200,14 +200,14 @@ class ChannelUserDictionary(collections.MutableMapping):
def __len__(self):
return sum([len(x) for x in self.channels])
def iteritems(self):
for (channel, ids) in self.channels.iteritems():
for (id, v) in ids.iteritems():
def items(self):
for (channel, ids) in self.channels.items():
for (id, v) in ids.items():
yield ((channel, id), v)
def keys(self):
L = []
for (k, _) in self.iteritems():
for (k, _) in self.items():
L.append(k)
return L
@ -252,7 +252,7 @@ class ChannelUserDB(ChannelUserDictionary):
def flush(self):
fd = utils.file.AtomicFile(self.filename, makeBackupIfSmaller=False)
writer = csv.writer(fd)
items = self.items()
items = list(self.items())
if not items:
log.debug('%s: Refusing to write blank file.',
self.__class__.__name__)

View File

@ -158,7 +158,6 @@ try:
log.debug(msg, *args)
fixer_names = ['fix_basestring',
'fix_dict',
'fix_imports',
'fix_long',
'fix_metaclass', 'fix_methodattrs',

View File

@ -59,7 +59,7 @@ def pack2Ints(i, j):
def dump(map, fd=sys.stdout):
"""Dumps a dictionary-structure in CDB format."""
for (key, value) in map.iteritems():
for (key, value) in map.items():
fd.write('+%s,%s:%s->%s\n' % (len(key), len(value), key, value))
def open_db(filename, mode='r', **kwargs):
@ -203,7 +203,7 @@ class Reader(utils.IterableMap):
def _match(self, key, pos):
return self._read(len(key), pos) == key
def iteritems(self):
def items(self):
# uses loop/hslots in a strange, non-re-entrant manner.
(self.loop,) = struct.unpack('<i', self._read(4, 0))
self.hslots = 2048
@ -334,7 +334,7 @@ class ReaderWriter(utils.IterableMap):
if removals or adds:
maker = Maker(self.filename)
cdb = Reader(self.filename)
for (key, value) in cdb.iteritems():
for (key, value) in cdb.items():
if key in removals:
continue
elif key in adds:
@ -344,7 +344,7 @@ class ReaderWriter(utils.IterableMap):
adds[key] = None
else:
maker.add(key, value)
for (key, value) in adds.iteritems():
for (key, value) in adds.items():
if value is not None:
maker.add(key, value)
cdb.close()
@ -416,9 +416,9 @@ class ReaderWriter(utils.IterableMap):
has_key = __contains__
def iteritems(self):
def items(self):
already = set()
for (key, value) in self.cdb.iteritems():
for (key, value) in self.cdb.items():
if key in self.removals or key in already:
continue
elif key in self.adds:
@ -426,7 +426,7 @@ class ReaderWriter(utils.IterableMap):
yield (key, self.adds[key])
else:
yield (key, value)
for (key, value) in self.adds.iteritems():
for (key, value) in self.adds.items():
if key not in already:
yield (key, value)
@ -452,8 +452,8 @@ class Shelf(ReaderWriter):
def __setitem__(self, key, value):
ReaderWriter.__setitem__(self, key, pickle.dumps(value, True))
def iteritems(self):
for (key, value) in ReaderWriter.iteritems(self):
def items(self):
for (key, value) in ReaderWriter.items(self):
yield (key, pickle.loads(value))

View File

@ -965,7 +965,7 @@ class getopts(context):
self.getopts = {}
self.getoptL = []
self.getoptLs = ''
for (name, spec) in getopts.iteritems():
for (name, spec) in getopts.items():
if spec == '':
if len(name) == 1:
self.getoptLs += name
@ -1025,7 +1025,7 @@ class State(object):
def essence(self):
st = State(self.types)
for (attr, value) in self.__dict__.iteritems():
for (attr, value) in self.__dict__.items():
if attr not in ('args', 'kwargs'):
setattr(st, attr, value)
return st

View File

@ -310,7 +310,7 @@ class CdbMapping(MappingInterface):
del self.db[str(id)]
def __iter__(self):
for (id, s) in self.db.iteritems():
for (id, s) in self.db.items():
if id != 'nextId':
yield (int(id), s)
@ -412,7 +412,7 @@ class Record(object):
self.defaults[name] = default
self.converters[name] = converter
seen = set()
for (name, value) in kwargs.iteritems():
for (name, value) in kwargs.items():
assert name in self.fields, 'name must be a record value.'
seen.add(name)
setattr(self, name, value)

View File

@ -99,7 +99,7 @@ def remove(name):
def run():
"""Runs the whole driver loop."""
for (name, driver) in _drivers.iteritems():
for (name, driver) in _drivers.items():
try:
if name not in _deadDrivers:
driver.run()

View File

@ -121,7 +121,7 @@ def reloadLocalesIfRequired():
def reloadLocales():
for pluginClass in i18nClasses.values():
pluginClass.loadLocale()
for command in internationalizedCommands.values():
for command in list(internationalizedCommands.values()):
internationalizeDocstring(command)
for function in internationalizedFunctions:
function.loadLocale()

View File

@ -477,11 +477,11 @@ class IrcChannel(object):
write('defaultAllow %s' % self.defaultAllow)
for capability in self.capabilities:
write('capability ' + capability)
bans = self.bans.items()
bans = list(self.bans.items())
utils.sortBy(operator.itemgetter(1), bans)
for (ban, expiration) in bans:
write('ban %s %d' % (ban, expiration))
ignores = self.ignores.items()
ignores = list(self.ignores.items())
utils.sortBy(operator.itemgetter(1), ignores)
for (ignore, expiration) in ignores:
write('ignore %s %d' % (ignore, expiration))
@ -653,7 +653,7 @@ class UsersDictionary(utils.IterableMap):
"""Flushes the database to its file."""
if not self.noFlush:
if self.filename is not None:
L = self.users.items()
L = list(self.users.items())
L.sort()
fd = utils.file.AtomicFile(self.filename)
for (id, u) in L:
@ -672,8 +672,8 @@ class UsersDictionary(utils.IterableMap):
world.flushers.remove(self.flush)
self.users.clear()
def iteritems(self):
return self.users.iteritems()
def items(self):
return self.users.items()
def getUserId(self, s):
"""Returns the user ID of a given name or hostmask."""
@ -682,12 +682,12 @@ class UsersDictionary(utils.IterableMap):
return self._hostmaskCache[s]
except KeyError:
ids = {}
for (id, user) in self.users.iteritems():
for (id, user) in self.users.items():
x = user.checkHostmask(s)
if x:
ids[id] = x
if len(ids) == 1:
id = ids.keys()[0]
id = list(ids.keys())[0]
self._hostmaskCache[s] = id
try:
self._hostmaskCache[id].add(s)
@ -699,7 +699,7 @@ class UsersDictionary(utils.IterableMap):
else:
log.error('Multiple matches found in user database. '
'Removing the offending hostmasks.')
for (id, hostmask) in ids.iteritems():
for (id, hostmask) in ids.items():
log.error('Removing %q from user %s.', hostmask, id)
self.users[id].removeHostmask(hostmask)
raise DuplicateHostmask('Ids %r matched.' % ids)
@ -777,7 +777,7 @@ class UsersDictionary(utils.IterableMap):
except KeyError:
pass
for hostmask in user.hostmasks:
for (i, u) in self.iteritems():
for (i, u) in self.items():
if i == user.id:
continue
elif u.checkHostmask(hostmask):
@ -847,7 +847,7 @@ class ChannelsDictionary(utils.IterableMap):
if not self.noFlush:
if self.filename is not None:
fd = utils.file.AtomicFile(self.filename)
for (channel, c) in self.channels.iteritems():
for (channel, c) in self.channels.items():
fd.write('channel %s' % channel)
fd.write(os.linesep)
c.preserve(fd, indent=' ')
@ -890,8 +890,8 @@ class ChannelsDictionary(utils.IterableMap):
self.channels[channel] = ircChannel
self.flush()
def iteritems(self):
return self.channels.iteritems()
def items(self):
return self.channels.items()
class IgnoresDB(object):

View File

@ -599,7 +599,7 @@ class IrcState(IrcCommandDispatcher):
chan.removeUser(user)
def doQuit(self, irc, msg):
for channel in self.channels.itervalues():
for channel in self.channels.values():
channel.removeUser(msg.nick)
if msg.nick in self.nicksToHostmasks:
# If we're quitting, it may not be.
@ -630,7 +630,7 @@ class IrcState(IrcCommandDispatcher):
del self.nicksToHostmasks[oldNick]
except KeyError:
pass
for channel in self.channels.itervalues():
for channel in self.channels.values():
channel.replaceUser(oldNick, newNick)

View File

@ -779,7 +779,7 @@ mircColors = IrcDict({
})
# We'll map integers to their string form so mircColor is simpler.
for (k, v) in mircColors.items():
for (k, v) in list(mircColors.items()):
if k is not None: # Ignore empty string for None.
sv = str(v)
mircColors[sv] = sv

View File

@ -378,7 +378,7 @@ class MetaFirewall(type):
if hasattr(base, '__firewalled__'):
cls.updateFirewalled(firewalled, base.__firewalled__)
cls.updateFirewalled(firewalled, classdict.get('__firewalled__', []))
for (attr, errorHandler) in firewalled.iteritems():
for (attr, errorHandler) in firewalled.items():
if attr in classdict:
classdict[attr] = firewall(classdict[attr], errorHandler)
return super(MetaFirewall, cls).__new__(cls, name, bases, classdict)

View File

@ -255,7 +255,7 @@ class Group(object):
#print '***>', _cache[name]
self.set(_cache[name])
if self._supplyDefault:
for (k, v) in _cache.iteritems():
for (k, v) in _cache.items():
if k.startswith(self._name):
rest = k[len(self._name)+1:] # +1 is for .
parts = split(rest)
@ -382,7 +382,7 @@ class Value(Group):
self._lastModified = time.time()
self.value = v
if self._supplyDefault:
for (name, v) in self._children.items():
for (name, v) in list(self._children.items()):
if v.__class__ is self.X:
self.unregister(name)
# We call the callback once everything is clean

View File

@ -206,7 +206,7 @@ class PluginTestCase(SupyTestCase):
ignoreDeprecation=True)
cb = plugin.loadPluginClass(self.irc, module)
self.irc.addCallback(TestInstance)
for (name, value) in self.config.iteritems():
for (name, value) in self.config.items():
group = conf.supybot
parts = registry.split(name)
if parts[0] == 'supybot':
@ -220,7 +220,7 @@ class PluginTestCase(SupyTestCase):
if self.__class__ in (PluginTestCase, ChannelPluginTestCase):
# Necessary because there's a test in here that shouldn\'t run.
return
for (group, original) in self.originals.iteritems():
for (group, original) in self.originals.items():
group.setValue(original)
ircdb.users.close()
ircdb.ignores.close()

View File

@ -36,6 +36,8 @@ import ast
import time
import types
import textwrap
import warnings
import functools
import traceback
import collections
@ -48,6 +50,18 @@ from .iter import imap
from supybot.i18n import PluginInternationalization
_ = PluginInternationalization()
def warn_non_constant_time(f):
@functools.wraps(f)
def newf(*args, **kwargs):
# This method takes linear time whereas the subclass could probably
# do it in constant time.
warnings.warn('subclass of IterableMap does provide an efficient '
'implementation of %s' % f.__name__,
DeprecationWarning)
return f(*args, **kwargs)
return newf
def abbrev(strings, d=None):
"""Returns a dictionary mapping unambiguous abbreviations to full forms."""
def eachSubstring(s):
@ -206,46 +220,35 @@ def exnToString(e):
return e.__class__.__name__
class IterableMap(object):
"""Define .iteritems() in a class and subclass this to get the other iters.
"""Define .items() in a class and subclass this to get the other iters.
"""
def iteritems(self):
if sys.version_info[0] >= 3 and hasattr(self, 'iteritems'):
def items(self):
if sys.version_info[0] >= 3 and hasattr(self, 'items'):
# For old plugins
return getattr(self, 'iteritems')() # avoid 2to3
return getattr(self, 'items')() # avoid 2to3
else:
raise NotImplementedError()
__iter__ = items
def iterkeys(self):
for (key, _) in self.iteritems():
def keys(self):
for (key, _) in self.items():
yield key
def itervalues(self):
for (_, value) in self.iteritems():
def values(self):
for (_, value) in self.items():
yield value
if sys.version_info[0] < 3:
# Our 2to3 fixers automatically rename iteritems/iterkeys/itervalues
# to items/keys/values
def items(self):
return list(self.iteritems())
def keys(self):
return list(self.iterkeys())
def values(self):
return list(self.itervalues())
__iter__ = iterkeys
else:
__iter__ = items
@warn_non_constant_time
def __len__(self):
ret = 0
for _ in self.iteritems():
for _ in self.items():
ret += 1
return ret
@warn_non_constant_time
def __bool__(self):
for _ in self.iteritems():
for _ in self.items():
return True
return False
__nonzero__ = __bool__
@ -290,12 +293,15 @@ class InsensitivePreservingDict(collections.MutableMapping):
def __len__(self):
return len(self.data)
def iteritems(self):
return self.data.itervalues()
def items(self):
return self.data.values()
def items(self):
return self.data.values()
def keys(self):
L = []
for (k, _) in self.iteritems():
for (k, _) in self.items():
L.append(k)
return L

View File

@ -381,14 +381,14 @@ class MaxLengthQueue(queue):
class TwoWayDictionary(dict):
__slots__ = ()
def __init__(self, seq=(), **kwargs):
if hasattr(seq, 'iteritems'):
seq = seq.iteritems()
if hasattr(seq, 'items'):
seq = seq.items()
elif hasattr(seq, 'items'):
seq = seq.items()
for (key, value) in seq:
self[key] = value
self[value] = key
for (key, value) in kwargs.iteritems():
for (key, value) in kwargs.items():
self[key] = value
self[value] = key
@ -445,8 +445,8 @@ class CacheDict(collections.MutableMapping):
def keys(self):
return self.d.keys()
def iteritems(self):
return self.d.iteritems()
def items(self):
return self.d.items()
def __iter__(self):
return iter(self.d)

View File

@ -192,7 +192,7 @@ def upkeep():
def makeDriversDie():
"""Kills drivers."""
log.info('Killing Driver objects.')
for driver in drivers._drivers.itervalues():
for driver in drivers._drivers.values():
driver.die()
def makeIrcsDie():

View File

@ -118,7 +118,7 @@ class GenTest(SupyTestCase):
def __setitem__(self, key, value):
self.L.append((key, value))
def iteritems(self):
def items(self):
for (k, v) in self.L:
yield (k, v)
AL = alist()
@ -128,12 +128,12 @@ class GenTest(SupyTestCase):
AL[3] = 4
self.failUnless(AL)
self.assertEqual(list(AL.items()), [(1, 2), (2, 3), (3, 4)])
self.assertEqual(list(AL.iteritems()), [(1, 2), (2, 3), (3, 4)])
self.assertEqual(list(AL.items()), [(1, 2), (2, 3), (3, 4)])
self.assertEqual(list(AL.keys()), [1, 2, 3])
if sys.version_info[0] < 3:
self.assertEqual(list(AL.iterkeys()), [1, 2, 3])
self.assertEqual(AL.values(), [2, 3, 4])
self.assertEqual(list(AL.itervalues()), [2, 3, 4])
self.assertEqual(list(AL.values()), [2, 3, 4])
self.assertEqual(len(AL), 3)
def testSortBy(self):