Skip to content

Commit

Permalink
Merge pull request #1961 from jackwilsdon/pep8-naming
Browse files Browse the repository at this point in the history
Add flake8 check for pep8 naming
  • Loading branch information
jackwilsdon committed Apr 28, 2016
2 parents 95252a5 + 730e1ef commit 48fff93
Show file tree
Hide file tree
Showing 28 changed files with 110 additions and 106 deletions.
2 changes: 1 addition & 1 deletion beets/autotag/hooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ def __init__(self):
self._penalties = {}

@LazyClassProperty
def _weights(cls):
def _weights(cls): # noqa
"""A dictionary from keys to floating-point weights.
"""
weights_view = config['match']['distance_weights']
Expand Down
8 changes: 4 additions & 4 deletions beets/dbcore/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -209,13 +209,13 @@ def _check_db(self, need_id=True):
# Essential field accessors.

@classmethod
def _type(self, key):
def _type(cls, key):
"""Get the type of a field, a `Type` instance.
If the field has no explicit type, it is given the base `Type`,
which does no conversion.
"""
return self._fields.get(key) or self._types.get(key) or types.DEFAULT
return cls._fields.get(key) or cls._types.get(key) or types.DEFAULT

def __getitem__(self, key):
"""Get the value for a field. Raise a KeyError if the field is
Expand Down Expand Up @@ -274,11 +274,11 @@ def keys(self, computed=False):
return base_keys

@classmethod
def all_keys(self):
def all_keys(cls):
"""Get a list of available keys for objects of this type.
Includes fixed and computed fields.
"""
return list(self._fields) + self._getters().keys()
return list(cls._fields) + cls._getters().keys()

# Act like a dictionary.

Expand Down
6 changes: 3 additions & 3 deletions beets/dbcore/query.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,9 +146,9 @@ def col_clause(self):
return self.field + " IS NULL", ()

@classmethod
def match(self, item):
def match(cls, item):
try:
return item[self.field] is None
return item[cls.field] is None
except KeyError:
return True

Expand Down Expand Up @@ -841,7 +841,7 @@ def is_slow(self):

class NullSort(Sort):
"""No sorting. Leave results unsorted."""
def sort(items):
def sort(self, items):
return items

def __nonzero__(self):
Expand Down
2 changes: 1 addition & 1 deletion beets/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ class BeetsLogger(ThreadLocalLevelLogger, StrFormatLogger):
my_manager.loggerClass = BeetsLogger


def getLogger(name=None):
def getLogger(name=None): # noqa
if name:
return my_manager.getLogger(name)
else:
Expand Down
22 changes: 11 additions & 11 deletions beets/util/artresizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,15 +149,15 @@ class Shareable(type):
lazily-created shared instance of ``MyClass`` while calling
``MyClass()`` to construct a new object works as usual.
"""
def __init__(cls, name, bases, dict):
super(Shareable, cls).__init__(name, bases, dict)
cls._instance = None
def __init__(self, name, bases, dict):
super(Shareable, self).__init__(name, bases, dict)
self._instance = None

@property
def shared(cls):
if cls._instance is None:
cls._instance = cls()
return cls._instance
def shared(self):
if self._instance is None:
self._instance = self()
return self._instance


class ArtResizer(object):
Expand Down Expand Up @@ -218,18 +218,18 @@ def _can_compare(self):
@staticmethod
def _check_method():
"""Return a tuple indicating an available method and its version."""
version = has_IM()
version = get_im_version()
if version:
return IMAGEMAGICK, version

version = has_PIL()
version = get_pil_version()
if version:
return PIL, version

return WEBPROXY, (0)


def has_IM():
def get_im_version():
"""Return Image Magick version or None if it is unavailable
Try invoking ImageMagick's "convert"."""
try:
Expand All @@ -248,7 +248,7 @@ def has_IM():
return None


def has_PIL():
def get_pil_version():
"""Return Image Magick version or None if it is unavailable
Try importing PIL."""
try:
Expand Down
2 changes: 1 addition & 1 deletion beets/util/confit.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ def __repr__(self):
)

@classmethod
def of(self, value):
def of(cls, value):
"""Given either a dictionary or a `ConfigSource` object, return
a `ConfigSource` object. This lets a function accept either type
of object as an argument.
Expand Down
13 changes: 8 additions & 5 deletions beetsplug/bucket.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@
from beets import plugins, ui


ASCII_DIGITS = string.digits + string.ascii_lowercase


class BucketError(Exception):
pass

Expand Down Expand Up @@ -155,23 +158,23 @@ def build_alpha_spans(alpha_spans_str, alpha_regexs):
[from...to]
"""
spans = []
ASCII_DIGITS = string.digits + string.ascii_lowercase

for elem in alpha_spans_str:
if elem in alpha_regexs:
spans.append(re.compile(alpha_regexs[elem]))
else:
bucket = sorted([x for x in elem.lower() if x.isalnum()])
if bucket:
beginIdx = ASCII_DIGITS.index(bucket[0])
endIdx = ASCII_DIGITS.index(bucket[-1])
begin_index = ASCII_DIGITS.index(bucket[0])
end_index = ASCII_DIGITS.index(bucket[-1])
else:
raise ui.UserError(u"invalid range defined for alpha bucket "
u"'%s': no alphanumeric character found" %
elem)
spans.append(
re.compile(
"^[" + ASCII_DIGITS[beginIdx:endIdx + 1] +
ASCII_DIGITS[beginIdx:endIdx + 1].upper() + "]"
"^[" + ASCII_DIGITS[begin_index:end_index + 1] +
ASCII_DIGITS[begin_index:end_index + 1].upper() + "]"
)
)
return spans
Expand Down
2 changes: 1 addition & 1 deletion beetsplug/export.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ class ExportFormat(object):
"""The output format type"""

@classmethod
def factory(self, type, **kwargs):
def factory(cls, type, **kwargs):
if type == "json":
if kwargs['file_path']:
return JsonFileFormat(**kwargs)
Expand Down
6 changes: 3 additions & 3 deletions beetsplug/fuzzy.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,13 @@

class FuzzyQuery(StringFieldQuery):
@classmethod
def string_match(self, pattern, val):
def string_match(cls, pattern, val):
# smartcase
if pattern.islower():
val = val.lower()
queryMatcher = difflib.SequenceMatcher(None, pattern, val)
query_matcher = difflib.SequenceMatcher(None, pattern, val)
threshold = config['fuzzy']['threshold'].as_number()
return queryMatcher.quick_ratio() >= threshold
return query_matcher.quick_ratio() >= threshold


class FuzzyPlugin(BeetsPlugin):
Expand Down
6 changes: 3 additions & 3 deletions beetsplug/thumbnails.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
from beets.plugins import BeetsPlugin
from beets.ui import Subcommand, decargs
from beets import util
from beets.util.artresizer import ArtResizer, has_IM, has_PIL
from beets.util.artresizer import ArtResizer, get_im_version, get_pil_version


BASE_DIR = os.path.join(BaseDirectory.xdg_cache_home, "thumbnails")
Expand Down Expand Up @@ -92,11 +92,11 @@ def _check_local_ok(self):
if not os.path.exists(dir):
os.makedirs(dir)

if has_IM():
if get_im_version():
self.write_metadata = write_metadata_im
tool = "IM"
else:
assert has_PIL() # since we're local
assert get_pil_version() # since we're local
self.write_metadata = write_metadata_pil
tool = "PIL"
self._log.debug(u"using {0} to write metadata", tool)
Expand Down
4 changes: 2 additions & 2 deletions test/_common.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,11 +167,11 @@ def tearDown(self):
beets.config.clear()
beets.config._materialized = False

def assertExists(self, path):
def assertExists(self, path): # noqa
self.assertTrue(os.path.exists(path),
u'file does not exist: {!r}'.format(path))

def assertNotExists(self, path):
def assertNotExists(self, path): # noqa
self.assertFalse(os.path.exists(path),
u'file exists: {!r}'.format((path)))

Expand Down
4 changes: 2 additions & 2 deletions test/test_art.py
Original file line number Diff line number Diff line change
Expand Up @@ -518,7 +518,7 @@ def tearDown(self):
fetchart.FileSystem.get = self.old_fs_source_get
super(ArtForAlbumTest, self).tearDown()

def _assertImageIsValidArt(self, image_file, should_exist):
def _assertImageIsValidArt(self, image_file, should_exist): # noqa
self.assertExists(image_file)
self.image_file = image_file

Expand All @@ -531,7 +531,7 @@ def _assertImageIsValidArt(self, image_file, should_exist):
else:
self.assertIsNone(candidate)

def _assertImageResized(self, image_file, should_resize):
def _assertImageResized(self, image_file, should_resize): # noqa
self.image_file = image_file
with patch.object(ArtResizer.shared, 'resize') as mock_resize:
self.plugin.art_for_album(self.album, [''], True)
Expand Down
14 changes: 7 additions & 7 deletions test/test_autotag.py
Original file line number Diff line number Diff line change
Expand Up @@ -940,13 +940,13 @@ class EnumTest(_common.TestCase):
Test Enum Subclasses defined in beets.util.enumeration
"""
def test_ordered_enum(self):
OrderedEnumTest = match.OrderedEnum('OrderedEnumTest', ['a', 'b', 'c'])
self.assertLess(OrderedEnumTest.a, OrderedEnumTest.b)
self.assertLess(OrderedEnumTest.a, OrderedEnumTest.c)
self.assertLess(OrderedEnumTest.b, OrderedEnumTest.c)
self.assertGreater(OrderedEnumTest.b, OrderedEnumTest.a)
self.assertGreater(OrderedEnumTest.c, OrderedEnumTest.a)
self.assertGreater(OrderedEnumTest.c, OrderedEnumTest.b)
OrderedEnumClass = match.OrderedEnum('OrderedEnumTest', ['a', 'b', 'c']) # noqa
self.assertLess(OrderedEnumClass.a, OrderedEnumClass.b)
self.assertLess(OrderedEnumClass.a, OrderedEnumClass.c)
self.assertLess(OrderedEnumClass.b, OrderedEnumClass.c)
self.assertGreater(OrderedEnumClass.b, OrderedEnumClass.a)
self.assertGreater(OrderedEnumClass.c, OrderedEnumClass.a)
self.assertGreater(OrderedEnumClass.c, OrderedEnumClass.b)


def suite():
Expand Down
4 changes: 2 additions & 2 deletions test/test_convert.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def tagged_copy_cmd(self, tag):
return u'sh -c "cp \'$source\' \'$dest\'; ' \
u'printf {0} >> \'$dest\'"'.format(tag)

def assertFileTag(self, path, tag):
def assertFileTag(self, path, tag): # noqa
"""Assert that the path is a file and the files content ends with `tag`.
"""
self.assertTrue(os.path.isfile(path),
Expand All @@ -50,7 +50,7 @@ def assertFileTag(self, path, tag):
self.assertEqual(f.read(), tag,
u'{0} is not tagged with {1}'.format(path, tag))

def assertNoFileTag(self, path, tag):
def assertNoFileTag(self, path, tag): # noqa
"""Assert that the path is a file and the files content does not
end with `tag`.
"""
Expand Down
4 changes: 2 additions & 2 deletions test/test_datequery.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,14 +62,14 @@ def test_unbounded_endpoints(self):
self.assertContains('..', date=datetime.min)
self.assertContains('..', '1000-01-01T00:00:00')

def assertContains(self, interval_pattern, date_pattern=None, date=None):
def assertContains(self, interval_pattern, date_pattern=None, date=None): # noqa
if date is None:
date = _date(date_pattern)
(start, end) = _parse_periods(interval_pattern)
interval = DateInterval.from_periods(start, end)
self.assertTrue(interval.contains(date))

def assertExcludes(self, interval_pattern, date_pattern):
def assertExcludes(self, interval_pattern, date_pattern): # noqa
date = _date(date_pattern)
(start, end) = _parse_periods(interval_pattern)
interval = DateInterval.from_periods(start, end)
Expand Down
4 changes: 2 additions & 2 deletions test/test_edit.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ def replace_contents(self, filename, log):

class EditMixin(object):
"""Helper containing some common functionality used for the Edit tests."""
def assertItemFieldsModified(self, library_items, items, fields=[],
def assertItemFieldsModified(self, library_items, items, fields=[], # noqa
allowed=['path']):
"""Assert that items in the library (`lib_items`) have different values
on the specified `fields` (and *only* on those fields), compared to
Expand Down Expand Up @@ -133,7 +133,7 @@ def tearDown(self):
self.teardown_beets()
self.unload_plugins()

def assertCounts(self, album_count=ALBUM_COUNT, track_count=TRACK_COUNT,
def assertCounts(self, album_count=ALBUM_COUNT, track_count=TRACK_COUNT, # noqa
write_call_count=TRACK_COUNT, title_starts_with=''):
"""Several common assertions on Album, Track and call counts."""
self.assertEqual(len(self.lib.albums()), album_count)
Expand Down
12 changes: 6 additions & 6 deletions test/test_importadded.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,19 +67,19 @@ def tearDown(self):
self.teardown_beets()
self.matcher.restore()

def findMediaFile(self, item):
def find_media_file(self, item):
"""Find the pre-import MediaFile for an Item"""
for m in self.media_files:
if m.title.replace('Tag', 'Applied') == item.title:
return m
raise AssertionError(u"No MediaFile found for Item " +
util.displayable_path(item.path))

def assertEqualTimes(self, first, second, msg=None):
def assertEqualTimes(self, first, second, msg=None): # noqa
"""For comparing file modification times at a sufficient precision"""
self.assertAlmostEqual(first, second, places=4, msg=msg)

def assertAlbumImport(self):
def assertAlbumImport(self): # noqa
self.importer.run()
album = self.lib.albums().get()
self.assertEqual(album.added, self.min_mtime)
Expand All @@ -102,7 +102,7 @@ def test_import_album_with_preserved_mtimes(self):
self.assertEqual(album.added, self.min_mtime)
for item in album.items():
self.assertEqualTimes(item.added, self.min_mtime)
mediafile_mtime = os.path.getmtime(self.findMediaFile(item).path)
mediafile_mtime = os.path.getmtime(self.find_media_file(item).path)
self.assertEqualTimes(item.mtime, mediafile_mtime)
self.assertEqualTimes(os.path.getmtime(item.path),
mediafile_mtime)
Expand Down Expand Up @@ -133,15 +133,15 @@ def test_import_singletons_with_added_dates(self):
self.config['import']['singletons'] = True
self.importer.run()
for item in self.lib.items():
mfile = self.findMediaFile(item)
mfile = self.find_media_file(item)
self.assertEqualTimes(item.added, os.path.getmtime(mfile.path))

def test_import_singletons_with_preserved_mtimes(self):
self.config['import']['singletons'] = True
self.config['importadded']['preserve_mtimes'] = True
self.importer.run()
for item in self.lib.items():
mediafile_mtime = os.path.getmtime(self.findMediaFile(item).path)
mediafile_mtime = os.path.getmtime(self.find_media_file(item).path)
self.assertEqualTimes(item.added, mediafile_mtime)
self.assertEqualTimes(item.mtime, mediafile_mtime)
self.assertEqualTimes(os.path.getmtime(item.path),
Expand Down
6 changes: 3 additions & 3 deletions test/test_importer.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,14 +125,14 @@ def _make_album_match(self, artist, album, tracks, distance=0, missing=0):
artist = artist.replace('Tag', 'Applied') + id
album = album.replace('Tag', 'Applied') + id

trackInfos = []
track_infos = []
for i in range(tracks - missing):
trackInfos.append(self._make_track_match(artist, album, i + 1))
track_infos.append(self._make_track_match(artist, album, i + 1))

return AlbumInfo(
artist=artist,
album=album,
tracks=trackInfos,
tracks=track_infos,
va=False,
album_id=u'albumid' + id,
artist_id=u'artistid' + id,
Expand Down
Loading

0 comments on commit 48fff93

Please sign in to comment.