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: if alias_plugin is None:
irc.error(_('Alias plugin is not loaded.'), Raise=True) irc.error(_('Alias plugin is not loaded.'), Raise=True)
errors = {} errors = {}
for (name, (command, locked, func)) in alias_plugin.aliases.items(): for (name, (command, locked, func)) in \
list(alias_plugin.aliases.items()):
try: try:
self._add_aka('global', name, command) self._add_aka('global', name, command)
except AkaError as e: 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. # XXX This should go. aliases should be a space separate list, etc.
group = conf.supybot.plugins.Alias.aliases group = conf.supybot.plugins.Alias.aliases
group2 = conf.supybot.plugins.Alias.escapedaliases group2 = conf.supybot.plugins.Alias.escapedaliases
for (name, alias) in registry._cache.iteritems(): for (name, alias) in registry._cache.items():
name = name.lower() name = name.lower()
if name.startswith('supybot.plugins.alias.aliases.'): if name.startswith('supybot.plugins.alias.aliases.'):
name = name[len('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. Returns the channels in which this bot is lobotomized.
""" """
L = [] L = []
for (channel, c) in ircdb.channels.iteritems(): for (channel, c) in ircdb.channels.items():
if c.lobotomized: if c.lobotomized:
chancap = ircdb.makeChannelCapability(channel, 'op') chancap = ircdb.makeChannelCapability(channel, 'op')
if ircdb.checkCapability(msg.prefix, 'admin') or \ if ircdb.checkCapability(msg.prefix, 'admin') or \

View File

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

View File

@ -222,7 +222,7 @@ class ChannelStats(callbacks.Plugin):
id = ircdb.users.getUserId(msg.prefix) id = ircdb.users.getUserId(msg.prefix)
except KeyError: except KeyError:
id = None 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 msg.nick in c.users:
if (channel, 'channelStats') not in self.db: if (channel, 'channelStats') not in self.db:
self.db[channel, 'channelStats'] = ChannelStat() self.db[channel, 'channelStats'] = ChannelStat()

View File

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

View File

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

View File

@ -358,9 +358,9 @@ class Factoids(callbacks.Plugin, plugins.ChannelDBHandler):
dl_metrics = [dameraulevenshtein(key, sourcekey) for sourcekey in flkeys] dl_metrics = [dameraulevenshtein(key, sourcekey) for sourcekey in flkeys]
dict_metrics = dict(list(zip(flkeys, dl_metrics))) dict_metrics = dict(list(zip(flkeys, dl_metrics)))
if min(dl_metrics) <= 2: 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: 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 [] return []

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -397,7 +397,7 @@ class Note(callbacks.Plugin):
else: else:
temp[note[1]] = [note[0]] temp[note[1]] = [note[0]]
notes = [] notes = []
for (k,v) in temp.iteritems(): for (k,v) in temp.items():
if '(private)' in k: if '(private)' in k:
k = k.replace('(private)', format('%b private', len(v))) k = k.replace('(private)', format('%b private', len(v)))
notes.append(format('%L %s', v, k)) 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 # 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 # children of supybot.plugins (the actual plugins) exist and can be
# loaded. # loaded.
for (name, s) in registry._cache.iteritems(): for (name, s) in registry._cache.items():
if 'alwaysLoadDefault' in name or 'alwaysLoadImportant' in name: if 'alwaysLoadDefault' in name or 'alwaysLoadImportant' in name:
continue continue
if name.startswith('supybot.plugins'): 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 Sort the list of 'long names' based on the number of contributions
associated with each. associated with each.
""" """
L = module.__contributors__.items() L = list(module.__contributors__.items())
def negativeSecondElement(x): def negativeSecondElement(x):
return -len(x[1]) return -len(x[1])
utils.sortBy(negativeSecondElement, L) utils.sortBy(negativeSecondElement, L)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -36,6 +36,8 @@ import ast
import time import time
import types import types
import textwrap import textwrap
import warnings
import functools
import traceback import traceback
import collections import collections
@ -48,6 +50,18 @@ from .iter import imap
from supybot.i18n import PluginInternationalization from supybot.i18n import PluginInternationalization
_ = 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): def abbrev(strings, d=None):
"""Returns a dictionary mapping unambiguous abbreviations to full forms.""" """Returns a dictionary mapping unambiguous abbreviations to full forms."""
def eachSubstring(s): def eachSubstring(s):
@ -206,46 +220,35 @@ def exnToString(e):
return e.__class__.__name__ return e.__class__.__name__
class IterableMap(object): 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): def items(self):
if sys.version_info[0] >= 3 and hasattr(self, 'iteritems'): if sys.version_info[0] >= 3 and hasattr(self, 'items'):
# For old plugins # For old plugins
return getattr(self, 'iteritems')() # avoid 2to3 return getattr(self, 'items')() # avoid 2to3
else: else:
raise NotImplementedError() raise NotImplementedError()
__iter__ = items
def iterkeys(self): def keys(self):
for (key, _) in self.iteritems(): for (key, _) in self.items():
yield key yield key
def itervalues(self): def values(self):
for (_, value) in self.iteritems(): for (_, value) in self.items():
yield value 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): def __len__(self):
ret = 0 ret = 0
for _ in self.iteritems(): for _ in self.items():
ret += 1 ret += 1
return ret return ret
@warn_non_constant_time
def __bool__(self): def __bool__(self):
for _ in self.iteritems(): for _ in self.items():
return True return True
return False return False
__nonzero__ = __bool__ __nonzero__ = __bool__
@ -290,12 +293,15 @@ class InsensitivePreservingDict(collections.MutableMapping):
def __len__(self): def __len__(self):
return len(self.data) return len(self.data)
def iteritems(self): def items(self):
return self.data.itervalues() return self.data.values()
def items(self):
return self.data.values()
def keys(self): def keys(self):
L = [] L = []
for (k, _) in self.iteritems(): for (k, _) in self.items():
L.append(k) L.append(k)
return L return L

View File

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

View File

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

View File

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