python3: reduce use of cmp when key can be used instead

cmp does not exist on python3
This commit is contained in:
Eli Schwartz 2019-03-26 12:46:40 -04:00
parent 06d8560ab2
commit 97ab4acce5
No known key found for this signature in database
GPG Key ID: CEB167EFB5722BD6
28 changed files with 41 additions and 64 deletions

View File

@ -279,7 +279,7 @@ def cli_docs(app):
info(bold('creating CLI documentation...'))
documented_cmds, undocumented_cmds = get_cli_docs()
documented_cmds.sort(cmp=lambda x, y: cmp(x[0], y[0]))
documented_cmds.sort(key=lambda x: x[0])
undocumented_cmds.sort()
documented = [' '*4 + c[0] for c in documented_cmds]

View File

@ -233,7 +233,7 @@ input_profiles = [InputProfile, SonyReaderInput, SonyReader300Input,
HanlinV5Input, CybookG3Input, CybookOpusInput, KindleInput, IlliadInput,
IRexDR1000Input, IRexDR800Input, NookInput]
input_profiles.sort(cmp=lambda x,y:cmp(x.name.lower(), y.name.lower()))
input_profiles.sort(key=lambda x: x.name.lower())
# }}}
@ -870,4 +870,4 @@ output_profiles = [
KindlePaperWhite3Output, KindleOasisOutput
]
output_profiles.sort(cmp=lambda x,y:cmp(x.name.lower(), y.name.lower()))
output_profiles.sort(key=lambda x: x.name.lower())

View File

@ -729,7 +729,7 @@ def initialize_plugins(perf=False):
if perf:
for x in sorted(times, key=lambda x: times[x]):
print('%50s: %.3f'%(x, times[x]))
_initialized_plugins.sort(cmp=lambda x,y:cmp(x.priority, y.priority), reverse=True)
_initialized_plugins.sort(key=lambda x: x.priority, reverse=True)
reread_filetype_plugins()
reread_metadata_plugins()

View File

@ -149,9 +149,7 @@ def main(opts, args, dbctx):
(not report_on or k in report_on)
]
categories.sort(
cmp=lambda x, y: cmp(x if x[0] != '#' else x[1:], y if y[0] != '#' else y[1:])
)
categories.sort(key=lambda x: x if x[0] != '#' else x[1:])
def fmtr(v):
v = v or 0

View File

@ -82,8 +82,7 @@ def debug(ioreg_to_tmp=False, buf=None, plugins=None,
out = partial(prints, file=buf)
devplugins = device_plugins() if plugins is None else plugins
devplugins = list(sorted(devplugins, cmp=lambda
x,y:cmp(x.__class__.__name__, y.__class__.__name__)))
devplugins = list(sorted(devplugins, key=lambda x: x.__class__.__name__))
if plugins is None:
for d in devplugins:
try:

View File

@ -321,7 +321,7 @@ class XMLCache(object):
# Only rebase ids of nodes that are immediate children of the
# record root (that way playlist/itemnodes are unaffected
items = root.xpath('child::*[@id]')
items.sort(cmp=lambda x,y:cmp(int(x.get('id')), int(y.get('id'))))
items.sort(key=lambda x: int(x.get('id')))
idmap = {}
for i, item in enumerate(items):
old = int(item.get('id'))

View File

@ -537,7 +537,7 @@ class Device(DeviceConfig, DevicePlugin):
if sz > 0:
nodes.append((x.split('/')[-1], sz))
nodes.sort(cmp=lambda x, y: cmp(x[1], y[1]))
nodes.sort(key=lambda x: x[1])
if not nodes:
return node
return nodes[-1][0]

View File

@ -995,8 +995,7 @@ def develop(): # {{{
drive_letters = set()
pprint(usb_devices)
print()
devplugins = list(sorted(device_plugins(), cmp=lambda
x,y:cmp(x.__class__.__name__, y.__class__.__name__)))
devplugins = list(sorted(device_plugins(), key=lambda x: x.__class__.__name__))
for dev in devplugins:
dev.startup()
for dev in devplugins:

View File

@ -821,7 +821,7 @@ OptionRecommendation(name='search_replace',
if not html_files:
raise ValueError(_('Could not find an e-book inside the archive'))
html_files = [(f, os.stat(f).st_size) for f in html_files]
html_files.sort(cmp=lambda x, y: cmp(x[1], y[1]))
html_files.sort(key=lambda x: x[1])
html_files = [f[0] for f in html_files]
for q in ('toc', 'index'):
for f in html_files:

View File

@ -670,8 +670,7 @@ class LitWriter(object):
def _build_dchunks(self):
ddata = []
directory = list(self._directory)
directory.sort(cmp=lambda x, y:
cmp(x.name.lower(), y.name.lower()))
directory.sort(key=lambda x: x.name.lower())
qrn = 1 + (1 << 2)
dchunk = io.BytesIO()
dcount = 0

View File

@ -32,7 +32,7 @@ def get_metadata(stream):
except:
pass
break
covers.sort(cmp=lambda x, y:cmp(len(x[0]), len(y[0])), reverse=True)
covers.sort(key=lambda x: len(x[0]), reverse=True)
idx = 0
if len(covers) > 1:
if covers[1][1] == covers[0][1]+'-standard':

View File

@ -41,8 +41,7 @@ def metadata_from_formats(formats, force_read_metadata=False, pattern=None):
def _metadata_from_formats(formats, force_read_metadata=False, pattern=None):
mi = MetaInformation(None, None)
formats.sort(cmp=lambda x,y: cmp(METADATA_PRIORITIES[path_to_ext(x)],
METADATA_PRIORITIES[path_to_ext(y)]))
formats.sort(key=lambda x: METADATA_PRIORITIES[path_to_ext(x)])
extensions = list(map(path_to_ext, formats))
if 'opf' in extensions:
opf = formats[extensions.index('opf')]
@ -241,4 +240,3 @@ def forked_read_metadata(path, tdir):
opf = metadata_to_opf(mi, default_lang='und')
with lopen(os.path.join(tdir, 'metadata.opf'), 'wb') as f:
f.write(opf)

View File

@ -28,7 +28,7 @@ class Clean(object):
else:
covers.append([self.oeb.guide[x], len(item.data)])
covers.sort(cmp=lambda x,y:cmp(x[1], y[1]), reverse=True)
covers.sort(key=lambda x: x[1], reverse=True)
if covers:
ref = covers[0][0]
if len(covers) > 1:
@ -53,4 +53,3 @@ class Clean(object):
if item.title and item.title.lower() == 'start':
continue
self.oeb.guide.remove(x)

View File

@ -169,7 +169,7 @@ class Column(object):
self._post_add()
def _post_add(self):
self.elements.sort(cmp=lambda x,y:cmp(x.bottom,y.bottom))
self.elements.sort(key=lambda x: x.bottom)
self.top = self.elements[0].top
self.bottom = self.elements[-1].bottom
self.left, self.right = sys.maxint, 0
@ -260,7 +260,7 @@ class Region(object):
def add(self, columns):
if not self.columns:
for x in sorted(columns, cmp=lambda x,y: cmp(x.left, y.left)):
for x in sorted(columns, key=lambda x: x.left):
self.columns.append(x)
else:
for i in range(len(columns)):
@ -458,7 +458,7 @@ class Page(object):
self.elements = list(self.texts)
for img in page.xpath('descendant::img'):
self.elements.append(Image(img, self.opts, self.log, idc))
self.elements.sort(cmp=lambda x,y:cmp(x.top, y.top))
self.elements.sort(key=lambda x: x.top)
def coalesce_fragments(self):
@ -580,7 +580,7 @@ class Page(object):
def sort_into_columns(self, elem, neighbors):
neighbors.add(elem)
neighbors = sorted(neighbors, cmp=lambda x,y:cmp(x.left, y.left))
neighbors = sorted(neighbors, key=lambda x: x.left)
if self.opts.verbose > 3:
self.log.debug('Neighbors:', [x.to_html() for x in neighbors])
columns = [Column()]
@ -595,7 +595,7 @@ class Page(object):
if not added:
columns.append(Column())
columns[-1].add(x)
columns.sort(cmp=lambda x,y:cmp(x.left, y.left))
columns.sort(key=lambda x: x.left)
return columns
def find_elements_in_row_of(self, x):

View File

@ -51,8 +51,7 @@ class LibraryUsageStats(object): # {{{
def write_stats(self):
locs = list(self.stats.keys())
locs.sort(cmp=lambda x, y: cmp(self.stats[x], self.stats[y]),
reverse=True)
locs.sort(key=lambda x: self.stats[x], reverse=True)
for key in locs[500:]:
self.stats.pop(key)
gprefs.set('library_usage_stats', self.stats)

View File

@ -93,7 +93,7 @@ class Catalog(QDialog, Ui_Dialog):
else:
info("No dynamic tab resources found for %s" % name)
self.widgets = sorted(self.widgets, cmp=lambda x,y:cmp(x.TITLE, y.TITLE))
self.widgets = sorted(self.widgets, key=lambda x: x.TITLE)
# Generate a sorted list of installed catalog formats/sync_enabled pairs
fmts = sorted([x[0] for x in self.fmts])

View File

@ -323,7 +323,7 @@ class BooksModel(QAbstractTableModel): # {{{
return 100000
return self.db.field_metadata[name]['rec_index']
self.column_map.sort(cmp=lambda x,y: cmp(col_idx(x), col_idx(y)))
self.column_map.sort(key=lambda x: col_idx(x))
for col in self.column_map:
if col in self.orig_headers:
self.headers[col] = self.orig_headers[col]

View File

@ -1031,7 +1031,7 @@ class BooksView(QTableView): # {{{
h.visualIndex(x) > -1]
if not pairs:
pairs = [(0, 0)]
pairs.sort(cmp=lambda x,y:cmp(x[1], y[1]))
pairs.sort(key=lambda x: x[1])
i = pairs[0][0]
index = self.model().index(row, i)
if for_sync:

View File

@ -69,7 +69,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
state = self.columns_state(defaults)
self.hidden_cols = state['hidden_columns']
positions = state['column_positions']
colmap.sort(cmp=lambda x,y: cmp(positions[x], positions[y]))
colmap.sort(key=lambda x: positions[x])
self.opt_columns.clear()
db = model.db
@ -248,12 +248,10 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
if 'ondevice' in hidden_cols:
hidden_cols.remove('ondevice')
def col_pos(x, y):
xidx = config_cols.index(x) if x in config_cols else sys.maxint
yidx = config_cols.index(y) if y in config_cols else sys.maxint
return cmp(xidx, yidx)
def col_pos(x):
return config_cols.index(x) if x in config_cols else sys.maxint
positions = {}
for i, col in enumerate((sorted(model.column_map, cmp=col_pos))):
for i, col in enumerate((sorted(model.column_map, key=col_pos))):
positions[col] = i
state = {'hidden_columns': hidden_cols, 'column_positions':positions}
self.gui.library_view.apply_state(state)

View File

@ -456,7 +456,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
if l != lang]
if lang != 'en':
items.append(('en', get_esc_lang('en')))
items.sort(cmp=lambda x, y: cmp(x[1].lower(), y[1].lower()))
items.sort(key=lambda x: x[1].lower())
choices = [(y, x) for x, y in items]
# Default language is the autodetected one
choices = [(get_language(lang), lang)] + choices

View File

@ -171,7 +171,7 @@ class Browser(QScrollArea): # {{{
self.category_names = category_names
categories = list(category_map.keys())
categories.sort(cmp=lambda x, y: cmp(category_map[x], category_map[y]))
categories.sort(key=lambda x: category_map[x])
self.category_map = OrderedDict()
for c in categories:
@ -181,7 +181,7 @@ class Browser(QScrollArea): # {{{
self.category_map[plugin.category].append(plugin)
for plugins in self.category_map.values():
plugins.sort(cmp=lambda x, y: cmp(x.name_order, y.name_order))
plugins.sort(key=lambda x: x.name_order)
self.widgets = []
self._layout = QVBoxLayout()

View File

@ -34,17 +34,6 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
self.db = gui.library_view.model().db
def initialize(self):
def field_cmp(x, y):
if x.startswith('#'):
if y.startswith('#'):
return cmp(x.lower(), y.lower())
else:
return 1
elif y.startswith('#'):
return -1
else:
return cmp(x.lower(), y.lower())
ConfigWidgetBase.initialize(self)
self.current_plugboards = copy.deepcopy(self.db.prefs.get('plugboards',{}))
@ -73,7 +62,7 @@ class ConfigWidget(ConfigWidgetBase, Ui_Form):
if n not in self.disabled_devices:
self.disabled_devices.append(n)
self.devices.sort(cmp=lambda x, y: cmp(x.lower(), y.lower()))
self.devices.sort(key=lambda x: x.lower())
self.devices.insert(1, plugboard_save_to_disk_value)
self.devices.insert(1, plugboard_content_server_value)
self.device_to_formats_map[plugboard_content_server_value] = \

View File

@ -61,7 +61,7 @@ class PluginModel(QAbstractItemModel, AdaptSQP): # {{{
self.categories = sorted(self._data.keys())
for plugins in self._data.values():
plugins.sort(cmp=lambda x, y: cmp(x.name.lower(), y.name.lower()))
plugins.sort(key=lambda x: x.name.lower())
def universal_set(self):
ans = set([])

View File

@ -427,7 +427,7 @@ def get_manufacturers():
def get_devices_of(manufacturer):
ans = [d for d in get_devices() if d.manufacturer == manufacturer]
return sorted(ans, cmp=lambda x,y:cmp(x.name, y.name))
return sorted(ans, key=lambda x: x.name)
class ManufacturerModel(QAbstractListModel):
@ -682,7 +682,7 @@ class LibraryPage(QWizardPage, LibraryUI):
if l != lang]
if lang != 'en':
items.append(('en', get_esc_lang('en')))
items.sort(cmp=lambda x, y: cmp(x[1], y[1]))
items.sort(key=lambda x: x[1])
for item in items:
self.language.addItem(item[1], (item[0]))
self.language.blockSignals(False)

View File

@ -216,7 +216,7 @@ class CustomColumns(object):
if data['is_multiple'] and data['datatype'] == 'text':
ans = ans.split(data['multiple_seps']['cache_to_list']) if ans else []
if data['display'].get('sort_alpha', False):
ans.sort(cmp=lambda x,y:cmp(x.lower(), y.lower()))
ans.sort(key=lambda x:x.lower())
return ans
def get_custom_extra(self, idx, label=None, num=None, index_is_id=False):
@ -243,7 +243,7 @@ class CustomColumns(object):
if data['is_multiple'] and data['datatype'] == 'text':
ans = ans.split(data['multiple_seps']['cache_to_list']) if ans else []
if data['display'].get('sort_alpha', False):
ans.sort(cmp=lambda x,y:cmp(x.lower(), y.lower()))
ans.sort(key=lambda x: x.lower())
if data['datatype'] != 'series':
return (ans, None)
ign,lt = self.custom_table_names(data['num'])

View File

@ -1018,7 +1018,7 @@ ALTER TABLE books ADD COLUMN isbn TEXT DEFAULT "" COLLATE NOCASE;
if not ans:
return []
ans = [id[0] for id in ans]
ans.sort(cmp=lambda x, y: cmp(self.series_index(x, True), self.series_index(y, True)))
ans.sort(key=lambda x: self.series_index(x, True))
return ans
def books_in_series_of(self, index, index_is_id=False):

View File

@ -98,8 +98,7 @@ def get_mx(host, verbose=0):
if verbose:
print('Find mail exchanger for', host)
answers = list(dns.resolver.query(host, 'MX'))
answers.sort(cmp=lambda x, y: cmp(int(getattr(x, 'preference', sys.maxint)),
int(getattr(y, 'preference', sys.maxint))))
answers.sort(key=lambda x: int(getattr(x, 'preference', sys.maxint)))
return [str(x.exchange) for x in answers if hasattr(x, 'exchange')]

View File

@ -760,7 +760,7 @@ class BasicNewsRecipe(Recipe):
in index are not in weights, they are assumed to have a weight of 0.
'''
weights = defaultdict(lambda: 0, weights)
index.sort(cmp=lambda x, y: cmp(weights[x], weights[y]))
index.sort(key=lambda x: weights[x])
return index
def parse_index(self):