replace iter{items|values} with six.iter{items|values}

This commit is contained in:
Johnny Robeson 2016-06-20 05:34:15 -04:00
parent 83f6ba3ce4
commit edb1cbc5fc
17 changed files with 42 additions and 35 deletions

View file

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

View file

@ -327,7 +327,7 @@ class Distance(object):
"""Return the maximum distance penalty (normalization factor). """Return the maximum distance penalty (normalization factor).
""" """
dist_max = 0.0 dist_max = 0.0
for key, penalty in self._penalties.iteritems(): for key, penalty in six.iteritems(self._penalties):
dist_max += len(penalty) * self._weights[key] dist_max += len(penalty) * self._weights[key]
return dist_max return dist_max
@ -336,7 +336,7 @@ class Distance(object):
"""Return the raw (denormalized) distance. """Return the raw (denormalized) distance.
""" """
dist_raw = 0.0 dist_raw = 0.0
for key, penalty in self._penalties.iteritems(): for key, penalty in six.iteritems(self._penalties):
dist_raw += sum(penalty) * self._weights[key] dist_raw += sum(penalty) * self._weights[key]
return dist_raw return dist_raw
@ -408,7 +408,7 @@ class Distance(object):
raise ValueError( raise ValueError(
u'`dist` must be a Distance object, not {0}'.format(type(dist)) u'`dist` must be a Distance object, not {0}'.format(type(dist))
) )
for key, penalties in dist._penalties.iteritems(): for key, penalties in six.iteritems(dist._penalties):
self._penalties.setdefault(key, []).extend(penalties) self._penalties.setdefault(key, []).extend(penalties)
# Adding components. # Adding components.

View file

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

View file

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

View file

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

View file

@ -807,7 +807,7 @@ class TerminalImportSession(importer.ImportSession):
if search_id: if search_id:
candidates, rec = autotag.tag_item( candidates, rec = autotag.tag_item(
task.item, search_ids=search_id.split()) task.item, search_ids=search_id.split())
elif choice in extra_ops.keys(): elif choice in list(extra_ops.keys()):
# Allow extra ops to automatically set the post-choice. # Allow extra ops to automatically set the post-choice.
post_choice = extra_ops[choice](self, task) post_choice = extra_ops[choice](self, task)
if isinstance(post_choice, importer.action): if isinstance(post_choice, importer.action):

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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