[Lint] Fix flake8 warnings

- Use six to silence flake8 undefined Python 2 names on Python 3.
- Fix W605 invalid escape sequence.
- Cleanup unused exception variables.
This commit is contained in:
Calum Lind 2018-10-25 10:52:25 +01:00
parent e2c7716ce2
commit 9dcd90056d
16 changed files with 38 additions and 35 deletions

View File

@ -147,9 +147,9 @@ encode_func[bool] = encode_bool
encode_func[str] = encode_string
encode_func[bytes] = encode_bytes
if PY2:
encode_func[long] = encode_int
encode_func[long] = encode_int # noqa: F821
encode_func[str] = encode_bytes
encode_func[unicode] = encode_string
encode_func[unicode] = encode_string # noqa: F821
def bencode(x):

View File

@ -758,7 +758,7 @@ def get_magnet_info(uri):
"""
tr0_param = 'tr.'
tr0_param_regex = re.compile('^tr.(\d+)=(\S+)')
tr0_param_regex = re.compile(r'^tr.(\d+)=(\S+)')
if not uri.startswith(MAGNET_SCHEME):
return {}

View File

@ -13,12 +13,11 @@ import logging
import traceback
from collections import defaultdict
from six import string_types
from twisted.internet import reactor
from twisted.internet.defer import DeferredList, fail, maybeDeferred, succeed
from twisted.internet.task import LoopingCall, deferLater
from deluge.common import PY2
log = logging.getLogger(__name__)
@ -325,7 +324,7 @@ class ComponentRegistry(object):
# Start all the components if names is empty
if not names:
names = list(self.components)
elif isinstance(names, str if not PY2 else basestring):
elif isinstance(names, string_types):
names = [names]
def on_depends_started(result, name):
@ -359,7 +358,7 @@ class ComponentRegistry(object):
"""
if not names:
names = list(self.components)
elif isinstance(names, str if not PY2 else basestring):
elif isinstance(names, string_types):
names = [names]
def on_dependents_stopped(result, name):
@ -399,7 +398,7 @@ class ComponentRegistry(object):
"""
if not names:
names = list(self.components)
elif isinstance(names, str if not PY2 else basestring):
elif isinstance(names, string_types):
names = [names]
deferreds = []
@ -425,7 +424,7 @@ class ComponentRegistry(object):
"""
if not names:
names = list(self.components)
elif isinstance(names, str if not PY2 else basestring):
elif isinstance(names, string_types):
names = [names]
deferreds = []

View File

@ -18,6 +18,7 @@ import tempfile
import threading
from base64 import b64decode, b64encode
from six import string_types
from twisted.internet import defer, reactor, task
from twisted.web.client import Agent, readBody
@ -25,7 +26,6 @@ import deluge.common
import deluge.component as component
from deluge import path_chooser_common
from deluge._libtorrent import LT_VERSION, lt
from deluge.common import PY2
from deluge.configmanager import ConfigManager, get_config_dir
from deluge.core.alertmanager import AlertManager
from deluge.core.authmanager import (
@ -666,7 +666,7 @@ class Core(component.Component):
def pause_torrent(self, torrent_id):
"""Pauses a torrent"""
log.debug('Pausing: %s', torrent_id)
if not isinstance(torrent_id, str if not PY2 else basestring):
if not isinstance(torrent_id, string_types):
self.pause_torrents(torrent_id)
else:
self.torrentmanager[torrent_id].pause()
@ -717,7 +717,7 @@ class Core(component.Component):
def resume_torrent(self, torrent_id):
"""Resumes a torrent"""
log.debug('Resuming: %s', torrent_id)
if not isinstance(torrent_id, str if not PY2 else basestring):
if not isinstance(torrent_id, string_types):
self.resume_torrents(torrent_id)
else:
self.torrentmanager[torrent_id].resume()
@ -900,7 +900,7 @@ class Core(component.Component):
if 'owner' in options and not self.authmanager.has_account(options['owner']):
raise DelugeError('Username "%s" is not known.' % options['owner'])
if isinstance(torrent_ids, str if not PY2 else basestring):
if isinstance(torrent_ids, string_types):
torrent_ids = [torrent_ids]
for torrent_id in torrent_ids:

View File

@ -11,8 +11,10 @@ from __future__ import unicode_literals
import logging
from six import string_types
import deluge.component as component
from deluge.common import PY2, TORRENT_STATE
from deluge.common import TORRENT_STATE
log = logging.getLogger(__name__)
@ -136,7 +138,7 @@ class FilterManager(component.Component):
# Sanitize input: filter-value must be a list of strings
for key, value in filter_dict.items():
if isinstance(value, str if not PY2 else basestring):
if isinstance(value, string_types):
filter_dict[key] = [value]
# Optimized filter for id

View File

@ -10,5 +10,5 @@ else:
try:
resource.setrlimit(resource.RLIMIT_NOFILE, (65536, 65536))
except (ValueError, resource.error) as ex:
# print('Failed to raise file descriptor limit:', ex)
pass
error = 'Failed to raise file descriptor limit: %s' % ex
# print(error)

View File

@ -11,6 +11,7 @@ from base64 import b64encode
from hashlib import sha1 as sha
import pytest
from six import integer_types
from twisted.internet import defer, reactor, task
from twisted.internet.error import CannotListenError
from twisted.python.failure import Failure
@ -22,7 +23,6 @@ from twisted.web.static import File
import deluge.common
import deluge.component as component
import deluge.core.torrent
from deluge.common import PY2
from deluge.core.core import Core
from deluge.core.rpcserver import RPCServer
from deluge.error import AddTorrentError, InvalidTorrentError
@ -429,7 +429,7 @@ class CoreTestCase(BaseTestCase):
def test_get_free_space(self):
space = self.core.get_free_space('.')
# get_free_space returns long on Python 2 (32-bit).
self.assertTrue(isinstance(space, int if not PY2 else (int, long)))
self.assertTrue(isinstance(space, integer_types))
self.assertTrue(space >= 0)
self.assertEqual(self.core.get_free_space('/someinvalidpath'), -1)

View File

@ -24,7 +24,7 @@ try:
from deluge.ui.gtkui.files_tab import FilesTab
from deluge.ui.gtkui.gtkui import DEFAULT_PREFS
from deluge.ui.gtkui.mainwindow import MainWindow
except ImportError as err:
except ImportError:
libs_available = False
setup_translations()
@ -101,7 +101,7 @@ class FilesTabTestCase(BaseTestCase):
def test_files_tab2(self):
if windows_check():
raise unittest.SkipTest('on windows \ != / for path names')
raise unittest.SkipTest('on windows \\ != / for path names')
self.filestab.files_list[self.t_id] = (
{'index': 0, 'path': '1/1/test_10.txt', 'offset': 0, 'size': 13},
{'index': 1, 'path': 'test_100.txt', 'offset': 13, 'size': 14},
@ -121,7 +121,7 @@ class FilesTabTestCase(BaseTestCase):
def test_files_tab3(self):
if windows_check():
raise unittest.SkipTest('on windows \ != / for path names')
raise unittest.SkipTest('on windows \\ != / for path names')
self.filestab.files_list[self.t_id] = (
{'index': 0, 'path': '1/test_10.txt', 'offset': 0, 'size': 13},
{'index': 1, 'path': 'test_100.txt', 'offset': 13, 'size': 14},
@ -158,7 +158,7 @@ class FilesTabTestCase(BaseTestCase):
def test_files_tab5(self):
if windows_check():
raise unittest.SkipTest('on windows \ != / for path names')
raise unittest.SkipTest('on windows \\ != / for path names')
self.filestab.files_list[self.t_id] = (
{'index': 0, 'path': '1/test_10.txt', 'offset': 0, 'size': 13},
{'index': 1, 'path': '2/test_100.txt', 'offset': 13, 'size': 14},

View File

@ -178,7 +178,7 @@ class DownloadFileTestCase(unittest.TestCase):
def test_download_with_rename(self):
if windows_check():
raise unittest.SkipTest('on windows \ != / for path names')
raise unittest.SkipTest('on windows \\ != / for path names')
url = self.get_url('rename?filename=renamed')
d = download_file(url, fname('original'))
@ -189,7 +189,7 @@ class DownloadFileTestCase(unittest.TestCase):
def test_download_with_rename_exists(self):
if windows_check():
raise unittest.SkipTest('on windows \ != / for path names')
raise unittest.SkipTest('on windows \\ != / for path names')
open(fname('renamed'), 'w').close()
url = self.get_url('rename?filename=renamed')
@ -201,7 +201,7 @@ class DownloadFileTestCase(unittest.TestCase):
def test_download_with_rename_sanitised(self):
if windows_check():
raise unittest.SkipTest('on windows \ != / for path names')
raise unittest.SkipTest('on windows \\ != / for path names')
url = self.get_url('rename?filename=/etc/passwd')
d = download_file(url, fname('original'))

View File

@ -53,7 +53,7 @@ class MetafileTestCase(unittest.TestCase):
def test_save_singlefile(self):
if windows_check():
raise unittest.SkipTest('on windows \ != / for path names')
raise unittest.SkipTest('on windows \\ != / for path names')
tmp_path = tempfile.mkstemp('testdata')[1]
with open(tmp_path, 'wb') as tmp_file:
tmp_file.write(b'a' * (2314 * 1024))

View File

@ -23,7 +23,7 @@ from .basetest import BaseTestCase
# Allow running other tests without GTKUI dependencies available
try:
from gobject import TYPE_UINT64
except ImportError as err:
except ImportError:
libs_available = False
TYPE_UINT64 = 'Whatever'
else:

View File

@ -57,7 +57,7 @@ def atom(src, token):
return token[-1].decode('string-escape')
elif token[1].isalpha():
# Parse Windows paths e.g. 'C:\\xyz' or 'C:/xyz'.
if next()[1] == ':' and next()[1] in '\/':
if next()[1] == ':' and next()[1] in '\\/':
return token[-1].decode('string-escape')
raise SyntaxError('malformed expression (%s)' % token[1])

View File

@ -16,6 +16,8 @@ import logging
import os
from base64 import b64encode
from six import unichr as chr
import deluge.common
from deluge.ui.client import client
from deluge.ui.common import TorrentInfo
@ -27,16 +29,16 @@ def _bracket_fixup(path):
if path.find('[') == -1 and path.find(']') == -1:
return path
sentinal = 256
while path.find(unichr(sentinal)) != -1:
while path.find(chr(sentinal)) != -1:
sentinal += 1
if sentinal > 65535:
log.error(
'Cannot fix brackets in path, path contains all possible sentinal characters'
)
return path
newpath = path.replace(']', unichr(sentinal))
newpath = path.replace(']', chr(sentinal))
newpath = newpath.replace('[', '[[]')
newpath = newpath.replace(unichr(sentinal), '[]]')
newpath = newpath.replace(chr(sentinal), '[]]')
return newpath

View File

@ -300,7 +300,7 @@ def add_string(
try:
screen.addstr(row, col, string.encode(encoding), color)
except curses.error as ex:
except curses.error:
# Ignore exception for writing offscreen.
pass

View File

@ -31,7 +31,7 @@ from twisted.internet.task import LoopingCall
try:
# Install twisted reactor, before any other modules import reactor.
reactor = gtk2reactor.install()
except ReactorAlreadyInstalledError as ex:
except ReactorAlreadyInstalledError:
# Running unit tests so trial already installed a rector
from twisted.internet import reactor

View File

@ -117,7 +117,7 @@ def start_ui():
ui = ui_entrypoints[selected_ui](
prog='%s %s' % (os.path.basename(sys.argv[0]), selected_ui), ui_args=ui_args
)
except KeyError as ex:
except KeyError:
log.error(
'Unable to find chosen UI: "%s". Please choose a different UI '
'or use "--set-default-ui" to change default UI.',