Walk back some six.iter* uses

In places where it doesn't much matter whether we use an iterator or the old
Python 2 list way, using the six name just hurts legibility.
This commit is contained in:
Adrian Sampson 2016-06-25 18:29:55 -07:00
parent 349a6e6c1d
commit e16cc58cb9
16 changed files with 32 additions and 41 deletions

View file

@ -25,7 +25,6 @@ from beets import config
from .hooks import AlbumInfo, TrackInfo, AlbumMatch, TrackMatch # noqa
from .match import tag_item, tag_album # noqa
from .match import Recommendation # noqa
import six
# Global logger.
log = logging.getLogger('beets')
@ -53,7 +52,7 @@ def apply_metadata(album_info, mapping):
"""Set the items' metadata to match an AlbumInfo object using a
mapping from Items to TrackInfo objects.
"""
for item, track_info in six.iteritems(mapping):
for item, track_info in mapping.items():
# Album, artist, track count.
if track_info.artist:
item.artist = track_info.artist

View file

@ -328,7 +328,7 @@ class Distance(object):
"""Return the maximum distance penalty (normalization factor).
"""
dist_max = 0.0
for key, penalty in six.iteritems(self._penalties):
for key, penalty in self._penalties.items():
dist_max += len(penalty) * self._weights[key]
return dist_max
@ -337,7 +337,7 @@ class Distance(object):
"""Return the raw (denormalized) distance.
"""
dist_raw = 0.0
for key, penalty in six.iteritems(self._penalties):
for key, penalty in self._penalties.items():
dist_raw += sum(penalty) * self._weights[key]
return dist_raw
@ -379,8 +379,6 @@ class Distance(object):
def __rsub__(self, other):
return other - self.distance
# Behave like a string
def __str__(self):
return "{0:.2f}".format(self.distance)
@ -411,7 +409,7 @@ class Distance(object):
raise ValueError(
u'`dist` must be a Distance object, not {0}'.format(type(dist))
)
for key, penalties in six.iteritems(dist._penalties):
for key, penalties in dist._penalties.items():
self._penalties.setdefault(key, []).extend(penalties)
# Adding components.

View file

@ -30,7 +30,6 @@ from beets.util import plurality
from beets.autotag import hooks
from beets.util.enumeration import OrderedEnum
from functools import reduce
import six
# Artist signals that indicate "various artists". These are used at the
# album level to determine whether a given release is likely a VA
@ -239,7 +238,7 @@ def distance(items, album_info, mapping):
# Tracks.
dist.tracks = {}
for item, track in six.iteritems(mapping):
for item, track in mapping.items():
dist.tracks[track] = track_distance(item, track, album_info.va)
dist.add('tracks', dist.tracks[track].distance)
@ -444,7 +443,7 @@ def tag_album(items, search_artist=None, search_album=None,
_add_candidate(items, candidates, info)
# Sort and get the recommendation.
candidates = sorted(six.itervalues(candidates))
candidates = sorted(candidates.values())
rec = _recommendation(candidates)
return cur_artist, cur_album, candidates, rec
@ -472,16 +471,16 @@ def tag_item(item, search_artist=None, search_title=None,
candidates[track_info.track_id] = \
hooks.TrackMatch(dist, track_info)
# If this is a good match, then don't keep searching.
rec = _recommendation(sorted(six.itervalues(candidates)))
rec = _recommendation(sorted(candidates.values()))
if rec == Recommendation.strong and \
not config['import']['timid']:
log.debug(u'Track ID match.')
return sorted(six.itervalues(candidates)), rec
return sorted(candidates.values()), rec
# If we're searching by ID, don't proceed.
if search_ids:
if candidates:
return sorted(six.itervalues(candidates)), rec
return sorted(candidates.values()), rec
else:
return [], Recommendation.none
@ -497,6 +496,6 @@ def tag_item(item, search_artist=None, search_title=None,
# Sort by distance and return with recommendation.
log.debug(u'Found {0} candidates.', len(candidates))
candidates = sorted(six.itervalues(candidates))
candidates = sorted(candidates.values())
rec = _recommendation(candidates)
return candidates, rec

View file

@ -334,7 +334,7 @@ def match_album(artist, album, tracks=None):
criteria['tracks'] = six.text_type(tracks)
# Abort if we have no search terms.
if not any(six.itervalues(criteria)):
if not any(criteria.values()):
return
try:
@ -360,7 +360,7 @@ def match_track(artist, title):
'recording': title.lower().strip(),
}
if not any(six.itervalues(criteria)):
if not any(criteria.values()):
return
try:

View file

@ -177,9 +177,9 @@ class Model(object):
ordinary construction are bypassed.
"""
obj = cls(db)
for key, value in six.iteritems(fixed_values):
for key, value in fixed_values.items():
obj._values_fixed[key] = cls._type(key).from_sql(value)
for key, value in six.iteritems(flex_values):
for key, value in flex_values.items():
obj._values_flex[key] = cls._type(key).from_sql(value)
return obj

View file

@ -853,7 +853,7 @@ class Server(BaseServer):
for name, itemid in iter(sorted(node.files.items())):
item = self.lib.get_item(itemid)
yield self._item_info(item)
for name, _ in iter(sorted(six.iteritems(node.dirs))):
for name, _ in iter(sorted(node.dirs.items())):
dirpath = self._path_join(path, name)
if dirpath.startswith(u"/"):
# Strip leading slash (libmpc rejects this).
@ -873,12 +873,12 @@ class Server(BaseServer):
yield u'file: ' + basepath
else:
# List a directory. Recurse into both directories and files.
for name, itemid in sorted(six.iteritems(node.files)):
for name, itemid in sorted(node.files.items()):
newpath = self._path_join(basepath, name)
# "yield from"
for v in self._listall(newpath, itemid, info):
yield v
for name, subdir in sorted(six.iteritems(node.dirs)):
for name, subdir in sorted(node.dirs.items()):
newpath = self._path_join(basepath, name)
yield u'directory: ' + newpath
for v in self._listall(newpath, subdir, info):
@ -903,11 +903,11 @@ class Server(BaseServer):
yield self.lib.get_item(node)
else:
# Recurse into a directory.
for name, itemid in sorted(six.iteritems(node.files)):
for name, itemid in sorted(node.files.items()):
# "yield from"
for v in self._all_items(itemid):
yield v
for name, subdir in sorted(six.iteritems(node.dirs)):
for name, subdir in sorted(node.dirs.items()):
for v in self._all_items(subdir):
yield v

View file

@ -122,7 +122,7 @@ def _all_releases(items):
for release_id in release_ids:
relcounts[release_id] += 1
for release_id, count in six.iteritems(relcounts):
for release_id, count in relcounts.items():
if float(count) / len(items) > COMMON_REL_THRESH:
yield release_id

View file

@ -330,7 +330,7 @@ class DuplicatesPlugin(BeetsPlugin):
"""Generate triples of keys, duplicate counts, and constituent objects.
"""
offset = 0 if full else 1
for k, objs in six.iteritems(self._group_by(objs, keys, strict)):
for k, objs in self._group_by(objs, keys, strict).items():
if len(objs) > 1:
objs = self._order(objs, tiebreak)
if merge:

View file

@ -601,7 +601,7 @@ class Wikipedia(RemoteArtSource):
try:
data = wikipedia_response.json()
results = data['query']['pages']
for _, result in six.iteritems(results):
for _, result in results.items():
image_url = result['imageinfo'][0]['url']
yield self._candidate(url=image_url,
match=Candidate.MATCH_EXACT)

View file

@ -12,7 +12,6 @@ import os
from beets import util
from beets import importer
from beets.plugins import BeetsPlugin
import six
class ImportAddedPlugin(BeetsPlugin):
@ -63,7 +62,7 @@ class ImportAddedPlugin(BeetsPlugin):
def record_reimported(self, task, session):
self.reimported_item_ids = set(item.id for item, replaced_items
in six.iteritems(task.replaced_items)
in task.replaced_items.items()
if replaced_items)
self.replaced_album_paths = set(task.replaced_albums.keys())

View file

@ -26,7 +26,6 @@ from beets import ui
from beets import mediafile
from beets.library import Item
from beets.util import displayable_path, normpath, syspath
import six
def tag_data(lib, args):
@ -74,7 +73,7 @@ def library_data_emitter(item):
def update_summary(summary, tags):
for key, value in six.iteritems(tags):
for key, value in tags.items():
if key not in summary:
summary[key] = value
elif summary[key] != value:
@ -97,7 +96,7 @@ def print_data(data, item=None, fmt=None):
path = displayable_path(item.path) if item else None
formatted = {}
for key, value in six.iteritems(data):
for key, value in data.items():
if isinstance(value, list):
formatted[key] = u'; '.join(value)
if value is not None:
@ -124,7 +123,7 @@ def print_data_keys(data, item=None):
"""
path = displayable_path(item.path) if item else None
formatted = []
for key, value in six.iteritems(data):
for key, value in data.items():
formatted.append(key)
if len(formatted) == 0:

View file

@ -232,7 +232,7 @@ class SymbolsReplaced(Backend):
@classmethod
def _encode(cls, s):
for old, new in six.iteritems(cls.REPLACEMENTS):
for old, new in cls.REPLACEMENTS.items():
s = re.sub(old, new, s)
return super(SymbolsReplaced, cls)._encode(s)

View file

@ -69,7 +69,7 @@ class RewritePlugin(BeetsPlugin):
rules['albumartist'].append((pattern, value))
# Replace each template field with the new rewriter function.
for fieldname, fieldrules in six.iteritems(rules):
for fieldname, fieldrules in rules.items():
getter = rewriter(fieldname, fieldrules)
self.template_fields[fieldname] = getter
if fieldname in library.Album._fields:

View file

@ -29,7 +29,6 @@ from beets.library import Item
from beets.util import plurality
from beets.autotag import AlbumInfo, TrackInfo
from beets import config
import six
class PluralityTest(_common.TestCase):
@ -612,7 +611,7 @@ class AssignmentTest(unittest.TestCase):
match.assign_items(items, trackinfo)
self.assertEqual(extra_items, [])
self.assertEqual(extra_tracks, [])
for item, info in six.iteritems(mapping):
for item, info in mapping.items():
self.assertEqual(items.index(item), trackinfo.index(info))

View file

@ -23,7 +23,6 @@ from test.test_ui_importer import TerminalImportSessionSetup
from test.test_importer import ImportHelper, AutotagStub
from beets.library import Item
from beetsplug.edit import EditPlugin
import six
class ModifyFileMocker(object):
@ -64,7 +63,7 @@ class ModifyFileMocker(object):
"""
with codecs.open(filename, 'r', encoding='utf8') as f:
contents = f.read()
for old, new_ in six.iteritems(self.replacements):
for old, new_ in self.replacements.items():
contents = contents.replace(old, new_)
with codecs.open(filename, 'w', encoding='utf8') as f:
f.write(contents)

View file

@ -14,7 +14,6 @@
# included in all copies or substantial portions of the Software.
from __future__ import division, absolute_import, print_function
import six
"""Tests for the `importadded` plugin."""
@ -125,7 +124,7 @@ class ImportAddedTest(unittest.TestCase, ImportHelper):
self.assertEqualTimes(album.added, album_added_before)
items_added_after = dict((item.path, item.added)
for item in album.items())
for item_path, added_after in six.iteritems(items_added_after):
for item_path, added_after in items_added_after.items():
self.assertEqualTimes(items_added_before[item_path], added_after,
u"reimport modified Item.added for " +
util.displayable_path(item_path))
@ -163,7 +162,7 @@ class ImportAddedTest(unittest.TestCase, ImportHelper):
# Verify the reimported items
items_added_after = dict((item.path, item.added)
for item in self.lib.items())
for item_path, added_after in six.iteritems(items_added_after):
for item_path, added_after in items_added_after.items():
self.assertEqualTimes(items_added_before[item_path], added_after,
u"reimport modified Item.added for " +
util.displayable_path(item_path))