From 37dd60538984a3917354b794a5c96b0a025f8e95 Mon Sep 17 00:00:00 2001 From: kaliko Date: Fri, 1 Oct 2021 20:29:57 +0200 Subject: [PATCH] Clean some linter warnings and errors --- sima/core.py | 9 +++++---- sima/launch.py | 4 +++- sima/lib/logger.py | 2 -- sima/lib/meta.py | 4 +++- sima/lib/simafm.py | 29 ++++++++++++++--------------- sima/lib/simastr.py | 3 --- sima/lib/track.py | 2 +- sima/mpdclient.py | 2 ++ sima/plugins/contrib/placeholder.py | 2 +- sima/plugins/core/history.py | 1 + sima/plugins/core/uniq.py | 2 +- sima/plugins/internal/genre.py | 4 ++-- sima/plugins/internal/lastfm.py | 3 ++- sima/plugins/internal/tags.py | 4 ++-- sima/utils/filelock.py | 2 +- sima/utils/leven.py | 2 ++ sima/utils/startopt.py | 2 +- sima/utils/utils.py | 1 - vinstall.py | 1 - 19 files changed, 41 insertions(+), 38 deletions(-) diff --git a/sima/core.py b/sima/core.py index ed4e0e1..4b7307e 100644 --- a/sima/core.py +++ b/sima/core.py @@ -37,7 +37,7 @@ class Sima(Daemon): """ def __init__(self, conf): - ## Set daemon + # Set daemon Daemon.__init__(self, conf.get('daemon', 'pidfile')) self.enabled = True self.config = conf @@ -80,7 +80,8 @@ class Sima(Daemon): @property def plugins(self): - return [plugin[1] for plugin in sorted(self._plugins, key=lambda pl: pl[0], reverse=True)] + return [plugin[1] for plugin in + sorted(self._plugins, key=lambda pl: pl[0], reverse=True)] def need_tracks(self): """Is the player in need for tracks""" @@ -126,7 +127,7 @@ class Sima(Daemon): self.log.debug(err) continue except PlayerError as err: - #TODO: unhandled Player exceptions + # TODO: unhandled Player exceptions self.log.warning('Unhandled player exception: %s', err) self.log.info('Got reconnected') break @@ -177,7 +178,7 @@ class Sima(Daemon): """Dispatching callbacks to plugins """ # hanging here until a monitored event is raised in the player - if getattr(self, 'changed', False): # first iteration exception + if getattr(self, 'changed', False): # first iteration exception self.changed = self.player.monitor() else: # first iteration goes through else self.changed = ['playlist', 'player', 'skipped'] diff --git a/sima/launch.py b/sima/launch.py index 1757d2b..4b77f89 100644 --- a/sima/launch.py +++ b/sima/launch.py @@ -148,7 +148,8 @@ def start(sopt, restart=False): for cplgn in core_plugins: logger.debug('Register core %(name)s (%(doc)s)', cplgn.info()) sima.register_core_plugin(cplgn) - logger.debug('core loaded, prioriy: %s', ' > '.join(map(str, sima.core_plugins))) + logger.debug('core loaded, prioriy: %s', + ' > '.join(map(str, sima.core_plugins))) # Loading internal plugins load_plugins(sima, 'internal') @@ -188,6 +189,7 @@ def run(sopt, restart=False): except Exception: # Unhandled exception exception_log() + # Script starts here def main(): """Entry point""" diff --git a/sima/lib/logger.py b/sima/lib/logger.py index b9b8b40..cab43fc 100644 --- a/sima/lib/logger.py +++ b/sima/lib/logger.py @@ -34,8 +34,6 @@ ERROR = logging.ERROR LOG_FORMATS = { DEBUG: '[{process}]{filename: >11}:{lineno: <3} {levelname: <7}: {message}', INFO: '{levelname: <7}: {message}', - #logging.DEBUG: '{asctime} {filename}:{lineno}({funcName}) ' - #'{levelname}: {message}', } DATE_FMT = "%Y-%m-%d %H:%M:%S" diff --git a/sima/lib/meta.py b/sima/lib/meta.py index 9e858a2..f118e82 100644 --- a/sima/lib/meta.py +++ b/sima/lib/meta.py @@ -31,6 +31,7 @@ UUID_RE = r'^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[89AB][a-f0-9]{3}-[a-f0-9]{12}$ # separator. It is used then to split back the string to tags list. SEPARATOR = chr(0x1F) # ASCII Unit Separator + def is_uuid4(uuid): """Controls MusicBrainz UUID4 format @@ -42,6 +43,7 @@ def is_uuid4(uuid): return True return False + class MetaException(Exception): """Generic Meta Exception""" @@ -170,7 +172,7 @@ class Meta: @property def names(self): """aliases + name""" - return self.__aliases | {self.__name,} + return self.__aliases | {self.__name, } @property @serialize diff --git a/sima/lib/simafm.py b/sima/lib/simafm.py index 18fe084..bd203f7 100644 --- a/sima/lib/simafm.py +++ b/sima/lib/simafm.py @@ -25,7 +25,6 @@ __version__ = '0.5.1' __author__ = 'Jack Kaliko' - from sima import LFM from sima.lib.meta import Artist from sima.lib.track import Track @@ -47,9 +46,9 @@ class SimaFM: :param BaseCache cache: Set a cache, defaults to `False`. """ - stats = {'etag':0, - 'ccontrol':0, - 'total':0} + stats = {'etag': 0, + 'ccontrol': 0, + 'total': 0} def __init__(self): self.http = HttpClient(cache=self.cache, stats=self.stats) @@ -69,11 +68,11 @@ class SimaFM: def _forge_payload(self, artist, method='similar', track=None): """Build payload """ - payloads = dict({'similar': {'method':'artist.getsimilar',}, - 'top': {'method':'artist.gettoptracks',}, - 'track': {'method':'track.getsimilar',}, - 'info': {'method':'artist.getinfo',}, - }) + payloads = dict({'similar': {'method': 'artist.getsimilar',}, + 'top': {'method': 'artist.gettoptracks',}, + 'track': {'method': 'track.getsimilar',}, + 'info': {'method': 'artist.getinfo',}, + }) payload = payloads.get(method) payload.update(api_key=LFM.get('apikey'), format='json') if not isinstance(artist, Artist): @@ -102,20 +101,20 @@ class SimaFM: ans = self.http(self.root_url, payload) try: ans.json() - except ValueError as err: + except ValueError: # Corrupted/malformed cache? cf. gitlab issue #35 raise WSError('Malformed json, try purging the cache: %s') - self._controls_answer(ans.json()) # pylint: disable=no-member + self._controls_answer(ans.json()) # pylint: disable=no-member # Artist might be found but return no 'artist' list… # cf. "Mulatu Astatqe" vs. "Mulatu Astatqé" with autocorrect=0 # json format is broken IMHO, xml is more consistent IIRC # Here what we got: # >>> {"similarartists":{"#text":"\n","artist":"Mulatu Astatqe"}} # autocorrect=1 should fix it, checking anyway. - simarts = ans.json().get('similarartists').get('artist') # pylint: disable=no-member + simarts = ans.json().get('similarartists').get('artist') # pylint: disable=no-member if not isinstance(simarts, list): raise WSError('Artist found but no similarities returned') - for art in ans.json().get('similarartists').get('artist'): # pylint: disable=no-member + for art in ans.json().get('similarartists').get('artist'): # pylint: disable=no-member yield Artist(name=art.get('name'), mbid=art.get('mbid', None)) def get_toptrack(self, artist): @@ -126,8 +125,8 @@ class SimaFM: """ payload = self._forge_payload(artist, method='top') ans = self.http(self.root_url, payload) - self._controls_answer(ans.json()) # pylint: disable=no-member - tops = ans.json().get('toptracks').get('track') # pylint: disable=no-member + self._controls_answer(ans.json()) # pylint: disable=no-member + tops = ans.json().get('toptracks').get('track') # pylint: disable=no-member art = {'artist': artist.name, 'musicbrainz_artistid': artist.mbid,} for song in tops: diff --git a/sima/lib/simastr.py b/sima/lib/simastr.py index cdb0195..033a994 100644 --- a/sima/lib/simastr.py +++ b/sima/lib/simastr.py @@ -118,18 +118,15 @@ class SimaStr(str): """ sea = SimaStr.reg_lead.search(self.stripped) if sea: - #print sea.groupdict() self.stripped = sea.group('root0') sea = SimaStr.reg_midl.search(self.stripped) if sea: - #print sea.groupdict() self.stripped = str().join([sea.group('root0'), ' ', sea.group('root1')]) sea = SimaStr.reg_trail.search(self.stripped) if sea: - #print sea.groupdict() self.stripped = sea.group('root0') def remove_diacritics(self): diff --git a/sima/lib/track.py b/sima/lib/track.py index a1a452a..f25d86d 100644 --- a/sima/lib/track.py +++ b/sima/lib/track.py @@ -118,7 +118,7 @@ class Track: @property def length(self): """Get a fancy duration as ``%H:%M:%S`` (use :attr:`duration` to get duration in second only)""" - temps = time.gmtime(self.duration) #TODO: returns a date not a duration + temps = time.gmtime(self.duration) # TODO: returns a date not a duration if temps.tm_hour: fmt = '%H:%M:%S' else: diff --git a/sima/mpdclient.py b/sima/mpdclient.py index d528b96..1347edd 100644 --- a/sima/mpdclient.py +++ b/sima/mpdclient.py @@ -50,6 +50,7 @@ def bl_artist(func): return result return wrapper + def set_artist_mbid(func): def wrapper(*args, **kwargs): cls = args[0] @@ -63,6 +64,7 @@ def set_artist_mbid(func): return result return wrapper + def tracks_wrapper(func): """Convert plain track mapping as returned by MPDClient into :py:obj:`sima.lib.track.Track` objects. This decorator accepts single track or list of tracks as input. diff --git a/sima/plugins/contrib/placeholder.py b/sima/plugins/contrib/placeholder.py index bd4f19c..71ad890 100644 --- a/sima/plugins/contrib/placeholder.py +++ b/sima/plugins/contrib/placeholder.py @@ -27,6 +27,7 @@ # local import from sima.lib.plugin import Plugin + class PlaceHolder(Plugin): """ Placeholder contrib plugin @@ -38,6 +39,5 @@ class PlaceHolder(Plugin): pass - # VIM MODLINE # vim: ai ts=4 sw=4 sts=4 expandtab diff --git a/sima/plugins/core/history.py b/sima/plugins/core/history.py index 3380870..57b57bd 100644 --- a/sima/plugins/core/history.py +++ b/sima/plugins/core/history.py @@ -28,6 +28,7 @@ from time import time # local import from ...lib.plugin import Plugin + class History(Plugin): """ History management diff --git a/sima/plugins/core/uniq.py b/sima/plugins/core/uniq.py index bc2ef54..1ad50f7 100644 --- a/sima/plugins/core/uniq.py +++ b/sima/plugins/core/uniq.py @@ -24,7 +24,7 @@ """ # standard library import -from os import getpid +from os import getpid from socket import getfqdn # third parties components diff --git a/sima/plugins/internal/genre.py b/sima/plugins/internal/genre.py index 264d8ab..713ee35 100644 --- a/sima/plugins/internal/genre.py +++ b/sima/plugins/internal/genre.py @@ -65,8 +65,8 @@ class Genre(AdvancedPlugin): def fetch_genres(self): """Fetches ,at most, nb-depth genre from history, and returns the nbgenres most present""" - depth = 10 # nb of genre to fetch from history for analysis - nbgenres = 2 # nb of genre to return + depth = 10 # nb of genre to fetch from history for analysis + nbgenres = 2 # nb of genre to return genres = [g[0] for g in self.sdb.fetch_genres_history(limit=depth)] if not genres: self.log.debug('No genre found in current track history') diff --git a/sima/plugins/internal/lastfm.py b/sima/plugins/internal/lastfm.py index 81a2b1c..457deb5 100644 --- a/sima/plugins/internal/lastfm.py +++ b/sima/plugins/internal/lastfm.py @@ -44,7 +44,8 @@ class Lastfm(WebService): persitent_cache = daemon.config.getboolean('lastfm', 'cache') if persitent_cache: CacheController.CACHE_ANYWAY = True - self.log.debug('Persistant cache enabled in %s', join(vardir, 'http', 'LastFM')) + self.log.debug('Persistant cache enabled in %s', + join(vardir, 'http', 'LastFM')) SimaFM.cache = FileCache(join(vardir, 'http', 'LastFM')) self.ws = SimaFM() diff --git a/sima/plugins/internal/tags.py b/sima/plugins/internal/tags.py index 2e1ddac..5e5d08c 100644 --- a/sima/plugins/internal/tags.py +++ b/sima/plugins/internal/tags.py @@ -42,13 +42,13 @@ def control_config(tags_config): if not tags_config.get('filter', None) and \ config_tags.isdisjoint(sup_tags): log.warning('Found no config for Tags plugin! ' - 'Need at least "filter" or a supported tag') + 'Need at least "filter" or a supported tag') log.info('Supported Tags are : %s', ', '.join(sup_tags)) # raise PluginException('plugin misconfiguration') return False if config_tags.difference(sup_tags): log.error('Found unsupported tag in config: %s', - config_tags.difference(sup_tags)) + config_tags.difference(sup_tags)) # raise PluginException('plugin misconfiguration') return False return True diff --git a/sima/utils/filelock.py b/sima/utils/filelock.py index 128815a..959f636 100644 --- a/sima/utils/filelock.py +++ b/sima/utils/filelock.py @@ -59,7 +59,7 @@ class FileLock: while True: try: self.filedsc = os.open(self.lockfile, - os.O_CREAT|os.O_EXCL|os.O_RDWR) + os.O_CREAT | os.O_EXCL | os.O_RDWR) break except OSError as err: if err.errno != errno.EEXIST: diff --git a/sima/utils/leven.py b/sima/utils/leven.py index 9f6eadb..d1ba274 100644 --- a/sima/utils/leven.py +++ b/sima/utils/leven.py @@ -18,6 +18,7 @@ # """Computes levenshtein distance/ratio""" + def levenshtein(a_st, b_st): """Computes the Levenshtein distance between two strings.""" n_a, m_b = len(a_st), len(b_st) @@ -38,6 +39,7 @@ def levenshtein(a_st, b_st): return current[n_a] + def levenshtein_ratio(string, strong): """ Compute levenshtein ratio. diff --git a/sima/utils/startopt.py b/sima/utils/startopt.py index bf9fcf4..f3499d1 100644 --- a/sima/utils/startopt.py +++ b/sima/utils/startopt.py @@ -19,7 +19,7 @@ # # -from argparse import ArgumentParser, RawDescriptionHelpFormatter, SUPPRESS +from argparse import ArgumentParser, RawDescriptionHelpFormatter from .utils import Wfile, Rfile, Wdir diff --git a/sima/utils/utils.py b/sima/utils/utils.py index c3e80d4..d226ef0 100644 --- a/sima/utils/utils.py +++ b/sima/utils/utils.py @@ -137,7 +137,6 @@ class Wfile(FileAction): if isdir(self._file): self.parser.error('need a file not a directory: {}'.format(self._file)) if not exists(self._dir): - #raise ArgumentError(self, '"{0}" does not exist'.format(self._dir)) self.parser.error('directory does not exist: {0}'.format(self._dir)) if not exists(self._file): # Is parent directory writable then diff --git a/vinstall.py b/vinstall.py index e71c953..102d8cd 100755 --- a/vinstall.py +++ b/vinstall.py @@ -2,7 +2,6 @@ # Copyright (C) 2013 Vinay Sajip. New BSD License. # Copyright (C) 2014, 2020 kaliko # -from __future__ import print_function REQ_VER = (3,4) import sys -- 2.39.5