[Lint] Autopep8 aggressive run

* Uses isinstance() instead of type()
 * Uses sorted() where possible
This commit is contained in:
Calum Lind 2015-11-04 11:12:21 +00:00
parent 05ab06e3a5
commit cde17925fc
22 changed files with 62 additions and 64 deletions

View File

@ -114,8 +114,7 @@ def encode_list(x, r):
def encode_dict(x, r):
r.append('d')
ilist = x.items()
ilist.sort()
ilist = sorted(x.items())
for k, v in ilist:
r.extend((str(len(k)), ':', k))
encode_func[type(v)](v, r)

View File

@ -54,7 +54,7 @@ def export(auth_level=AUTH_LEVEL_DEFAULT):
return func
if type(auth_level) is FunctionType:
if isinstance(auth_level, FunctionType):
func = auth_level
auth_level = AUTH_LEVEL_DEFAULT
return wrap(func)
@ -116,7 +116,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
:type data: tuple
"""
if type(request) is not tuple:
if not isinstance(request, tuple):
log.debug("Received invalid message: type is not tuple")
return

View File

@ -681,7 +681,7 @@ class TorrentManager(component.Component):
try:
log.debug("Saving %s to: %s", filename, filepath)
os.rename(filepath_tmp, filepath)
except OSError, ex:
except OSError as ex:
log.error("Failed to set new state file %s: %s", filepath, ex)
if os.path.isfile(filepath_bak):
log.info("Restoring backup of state from: %s", filepath_bak)
@ -796,7 +796,7 @@ class TorrentManager(component.Component):
try:
log.debug("Saving %s to: %s", filename, filepath)
os.rename(filepath_tmp, filepath)
except OSError, ex:
except OSError as ex:
log.error("Failed to set new file %s: %s", filepath, ex)
if os.path.isfile(filepath_bak):
log.info("Restoring backup from: %s", filepath_bak)

View File

@ -158,8 +158,7 @@ def makeinfo(path, piece_length, progress, name=None, content_type=None, private
path = os.path.abspath(path)
piece_count = 0
if os.path.isdir(path):
subs = subfiles(path)
subs.sort()
subs = sorted(subfiles(path))
pieces = []
sh = sha()
done = 0

View File

@ -75,7 +75,7 @@ class Core(CorePluginBase):
self.reader = create_reader(self.config["list_type"], self.config["list_compression"])
if type(self.config["last_update"]) is not float:
if not isinstance(self.config["last_update"], float):
self.config.config["last_update"] = 0.0
update_now = False

View File

@ -131,7 +131,7 @@ class ExecutePreferences(object):
for child in children:
command_id, event = child.get_name().split("_")
for widget in child.get_children():
if type(widget) == gtk.Entry:
if isinstance(widget, gtk.Entry):
command = widget.get_text()
client.execute.save_command(command_id, event, command)

View File

@ -178,7 +178,7 @@ class CoreTestCase(BaseTestCase):
def test_true(val):
self.assertTrue(val[0][0] == "torrentidthatdoesntexist")
self.assertTrue(type(val[0][1]) == InvalidTorrentError)
self.assertTrue(isinstance(val[0][1], InvalidTorrentError))
d.addCallback(test_true)
return d
@ -208,9 +208,9 @@ class CoreTestCase(BaseTestCase):
def test_ret(val):
self.assertTrue(len(val) == 2)
self.assertTrue(val[0][0] == "invalidid1")
self.assertTrue(type(val[0][1]) == InvalidTorrentError)
self.assertTrue(isinstance(val[0][1], InvalidTorrentError))
self.assertTrue(val[1][0] == "invalidid2")
self.assertTrue(type(val[1][1]) == InvalidTorrentError)
self.assertTrue(isinstance(val[1][1], InvalidTorrentError))
d.addCallback(test_ret)
return d
@ -227,7 +227,7 @@ class CoreTestCase(BaseTestCase):
def test_get_free_space(self):
space = self.core.get_free_space(".")
self.assertTrue(type(space) in (int, long))
self.assertTrue(isinstance(space, (int, long)))
self.assertTrue(space >= 0)
self.assertEquals(self.core.get_free_space("/someinvalidpath"), -1)

View File

@ -113,21 +113,21 @@ class TorrentTestCase(unittest.TestCase):
return deferLater(reactor, 0.1, self.assert_state, torrent, orig_state)
def test_torrent_error_resume_data_unaltered(self):
resume_data = {'active_time': 13399L, 'num_incomplete': 16777215L, 'announce_to_lsd': 1L, 'seed_mode': 0L,
'pieces': '\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01', 'paused': 0L,
'seeding_time': 13399L, 'last_scrape': 13399L,
'info-hash': '-\xc5\xd0\xe7\x1af\xfeid\x9ad\r9\xcb\x00\xa2YpIs', 'max_uploads': 16777215L,
'max_connections': 16777215L, 'num_downloaders': 16777215L, 'total_downloaded': 0L,
'file-format': 'libtorrent resume file', 'peers6': '', 'added_time': 1411826665L,
'banned_peers6': '', 'file_priority': [1L], 'last_seen_complete': 0L, 'total_uploaded': 0L,
resume_data = {'active_time': 13399, 'num_incomplete': 16777215, 'announce_to_lsd': 1, 'seed_mode': 0,
'pieces': '\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01', 'paused': 0,
'seeding_time': 13399, 'last_scrape': 13399,
'info-hash': '-\xc5\xd0\xe7\x1af\xfeid\x9ad\r9\xcb\x00\xa2YpIs', 'max_uploads': 16777215,
'max_connections': 16777215, 'num_downloaders': 16777215, 'total_downloaded': 0,
'file-format': 'libtorrent resume file', 'peers6': '', 'added_time': 1411826665,
'banned_peers6': '', 'file_priority': [1], 'last_seen_complete': 0, 'total_uploaded': 0,
'piece_priority': '\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01',
'file-version': 1L, 'announce_to_dht': 1L, 'auto_managed': 1L, 'upload_rate_limit': 0L,
'completed_time': 1411826665L, 'allocation': 'sparse', 'blocks per piece': 2L,
'download_rate_limit': 0L, 'libtorrent-version': '0.16.17.0', 'banned_peers': '',
'num_seeds': 16777215L, 'sequential_download': 0L, 'announce_to_trackers': 1L,
'peers': '\n\x00\x02\x0f=\xc6SC\x17]\xd8}\x7f\x00\x00\x01=\xc6', 'finished_time': 13399L,
'last_upload': 13399L, 'trackers': [[]], 'super_seeding': 0L,
'file sizes': [[512000L, 1411826586L]], 'last_download': 13399L}
'file-version': 1, 'announce_to_dht': 1, 'auto_managed': 1, 'upload_rate_limit': 0,
'completed_time': 1411826665, 'allocation': 'sparse', 'blocks per piece': 2,
'download_rate_limit': 0, 'libtorrent-version': '0.16.17.0', 'banned_peers': '',
'num_seeds': 16777215, 'sequential_download': 0, 'announce_to_trackers': 1,
'peers': '\n\x00\x02\x0f=\xc6SC\x17]\xd8}\x7f\x00\x00\x01=\xc6', 'finished_time': 13399,
'last_upload': 13399, 'trackers': [[]], 'super_seeding': 0,
'file sizes': [[512000, 1411826586]], 'last_download': 13399}
torrent_state = TorrentState(
torrent_id='2dc5d0e71a66fe69649a640d39cb00a259704973',
filename='test_torrent.file.torrent',

View File

@ -92,7 +92,7 @@ class DelugeRPCProtocol(DelugeTransferProtocol):
:param request: a tuple that should be either a RPCResponse, RCPError or RPCSignal
"""
if type(request) is not tuple:
if not isinstance(request, tuple):
log.debug("Received invalid message: type is not tuple")
return
if len(request) < 3:

View File

@ -127,7 +127,7 @@ class TorrentInfo(object):
file_tree.walk(walk)
else:
def walk(path, item):
if type(item) is dict:
if isinstance(item, dict):
return item
return [paths[path]["index"], paths[path]["length"], True]
@ -363,7 +363,7 @@ class FileTree(object):
:rtype: dictionary
"""
def to_tuple(path, item):
if type(item) is dict:
if isinstance(item, dict):
return item
return tuple(item)
self.walk(to_tuple)
@ -382,7 +382,7 @@ class FileTree(object):
def walk(directory, parent_path):
for path in directory.keys():
full_path = os.path.join(parent_path, path)
if type(directory[path]) is dict:
if isinstance(directory[path], dict):
directory[path] = callback(full_path, directory[path]) or directory[path]
walk(directory[path], full_path)
else:
@ -395,7 +395,7 @@ class FileTree(object):
def write(path, item):
depth = path.count("/")
path = os.path.basename(path)
path = type(item) is dict and path + "/" or path
path = isinstance(item, dict) and path + "/" or path
lines.append(" " * depth + path)
self.walk(write)
return "\n".join(lines)

View File

@ -81,16 +81,17 @@ class Command(BaseCommand):
def _get_config(self, *args, **options):
def _on_get_config(config):
keys = config.keys()
keys.sort()
keys = sorted(config.keys())
s = ""
for key in keys:
if args and key not in args:
continue
color = "{!white,black,bold!}"
value = config[key]
if type(value) in colors.type_color:
try:
color = colors.type_color[type(value)]
except KeyError:
pass
# We need to format dicts for printing
if isinstance(value, dict):
@ -115,7 +116,7 @@ class Command(BaseCommand):
self.console.write("{!error!}The key '%s' is invalid!" % key)
return
if type(config[key]) != type(val):
if not isinstance(config[key], type(val)):
try:
val = type(config[key])(val)
except TypeError:

View File

@ -94,11 +94,12 @@ class EventLog(component.Component):
def on_config_value_changed_event(self, key, value):
color = "{!white,black,bold!}"
if type(value) in colors.type_color:
try:
color = colors.type_color[type(value)]
except KeyError:
pass
self.write("ConfigValueChanged: {!input!}%s: %s%s" %
(key, color, value))
self.write("ConfigValueChanged: {!input!}%s: %s%s" % (key, color, value))
def write(self, s):
current_time = time.localtime()

View File

@ -60,7 +60,7 @@ class InfoField(NoInput):
def set_value(self, v):
self.value = v
if type(v) == float:
if isinstance(v, float):
self.txt = "%s %.2f" % (self.label, self.value)
else:
self.txt = "%s %s" % (self.label, self.value)

View File

@ -465,7 +465,7 @@ class ListView:
"""Adds a column to the ListView"""
# Add the column types to liststore_columns
column_indices = []
if type(col_types) is list:
if isinstance(col_types, list):
for col_type in col_types:
self.liststore_columns.append(col_type)
column_indices.append(len(self.liststore_columns) - 1)

View File

@ -119,7 +119,7 @@ class ValueList(object):
:type scroll_to_row: boolean
"""
if not (type(paths) is list or type(paths) is tuple):
if not (isinstance(paths, list) or isinstance(paths, tuple)):
return
sel = None
if preserve_selection:
@ -1142,7 +1142,7 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject):
return self.auto_completer.auto_complete_enabled
def set_auto_complete_enabled(self, enable):
if not type(enable) is bool:
if not isinstance(enable, bool):
return
self.auto_completer.auto_complete_enabled = enable
@ -1150,7 +1150,7 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject):
return self.show_folder_name_on_button
def set_show_folder_name_on_button(self, show):
if not type(show) is bool:
if not isinstance(show, bool):
return
self.show_folder_name_on_button = show
self._set_path_entry_filechooser_widths()
@ -1165,7 +1165,7 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject):
By setting filechooser disabled, in will not be possible
to change the settings in the properties.
"""
if not type(enable) is bool:
if not isinstance(enable, bool):
return
self.filechooser_enabled = enable
if not enable:
@ -1178,7 +1178,7 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject):
"""
Set file chooser button entry visible
"""
if not type(visible) is bool:
if not isinstance(visible, bool):
return
if update:
self.filechooser_visible = visible
@ -1198,7 +1198,7 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject):
"""
Set the path entry visible
"""
if not type(visible) is bool:
if not isinstance(visible, bool):
return
self.path_entry_visible = visible
if visible:
@ -1214,7 +1214,7 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject):
"""
Enable/disable showing hidden files on path completion
"""
if not type(show) is bool:
if not isinstance(show, bool):
return
self.auto_completer.completion_popup.show_hidden_files = show
if do_completion:
@ -1226,7 +1226,7 @@ class PathChooserComboBox(gtk.HBox, StoredValuesPopup, gobject.GObject):
"""
Enable/disable the config properties
"""
if not type(enable) is bool:
if not isinstance(enable, bool):
return
self.properties_enabled = enable
if self.properties_enabled:

View File

@ -424,7 +424,7 @@ class Preferences(component.Component):
# Update the widgets accordingly
for key in core_widgets.keys():
modifier = core_widgets[key][0]
if type(key) is str:
if isinstance(key, str):
widget = self.builder.get_object(key)
else:
widget = key
@ -434,9 +434,9 @@ class Preferences(component.Component):
if self.is_connected:
value = core_widgets[key][1]
from types import FunctionType
if type(value) is FunctionType:
if isinstance(value, FunctionType):
value = value()
elif type(value) is str:
elif isinstance(value, str):
value = self.core_config[value]
elif modifier:
value = {"active": False, "not_active": False, "value": 0, "text": "", "path_chooser": ""}[modifier]
@ -456,7 +456,7 @@ class Preferences(component.Component):
if self.is_connected:
for key in core_widgets.keys():
if type(key) is str:
if isinstance(key, str):
widget = self.builder.get_object(key)
else:
widget = key
@ -803,7 +803,7 @@ class Preferences(component.Component):
widget = self.builder.get_object(widget_name)
key = widget_name[len("label_cache_"):]
value = self.cache_status[key]
if type(value) == float:
if isinstance(value, float):
value = "%.2f" % value
else:
value = str(value)

View File

@ -31,7 +31,7 @@ class RemoveTorrentDialog(object):
"""
def __init__(self, torrent_ids, delete_files=False):
if type(torrent_ids) != list and type(torrent_ids) != tuple:
if not isinstance(torrent_ids, list) and not isinstance(torrent_ids, tuple):
raise TypeError("requires a list of torrent_ids")
if not torrent_ids:

View File

@ -128,9 +128,8 @@ class TorrentDetails(component.Component):
# Determine insert position based on weight
# weights is a list of visible tab names in weight order
weights = [(tab.weight, name) for name, tab in self.tabs.iteritems() if tab.is_visible]
weights = sorted([(tab.weight, name) for name, tab in self.tabs.iteritems() if tab.is_visible])
weights.sort()
log.debug("weights: %s", weights)
log.debug("weight of tab: %s", weight)

View File

@ -126,7 +126,7 @@ class Auth(JSONComponent):
log.debug("Creating session for %s", login)
config = component.get("DelugeWeb").config
if type(config["sessions"]) is list:
if isinstance(config["sessions"], list):
config.config["sessions"] = {}
config["sessions"][session_id] = {

View File

@ -67,7 +67,7 @@ def export(auth_level=AUTH_LEVEL_DEFAULT):
func._json_auth_level = auth_level
return func
if type(auth_level) is FunctionType:
if isinstance(auth_level, FunctionType):
func = auth_level
auth_level = AUTH_LEVEL_DEFAULT
return wrap(func)

View File

@ -335,8 +335,7 @@ class ScriptResource(resource.Resource, component.Component):
filepath, recurse = _scripts[path]
for root, dirnames, filenames in os.walk(filepath):
dirnames.sort(reverse=True)
files = fnmatch.filter(filenames, "*.js")
files.sort()
files = sorted(fnmatch.filter(filenames, "*.js"))
order_file = os.path.join(root, ".order")
if os.path.isfile(order_file):

View File

@ -69,8 +69,8 @@ disable=missing-docstring, invalid-name, old-style-class, bad-continuation,
no-member, not-callable, no-name-in-module, super-on-old-class,
locally-disabled,
R,
unused-argument, fixme, protected-access, import-error, unidiomatic-typecheck,
unused-variable, global-statement, attribute-defined-outside-init, arguments-differ,
unused-argument, fixme, protected-access, import-error, unused-variable,
global-statement, attribute-defined-outside-init, arguments-differ,
no-init, non-parent-init-called, super-init-not-called, signature-differs,
broad-except, pointless-except