python3: PEP 3114 compliance for next() and iterators

This commit is contained in:
Eli Schwartz 2019-03-21 14:03:54 -04:00
parent 9ecadb9c13
commit 391ca722e0
No known key found for this signature in database
GPG Key ID: CEB167EFB5722BD6
29 changed files with 62 additions and 64 deletions

View File

@ -212,7 +212,7 @@ class Plugin(object): # {{{
For example to load an image::
pixmap = QPixmap()
pixmap.loadFromData(self.load_resources(['images/icon.png']).itervalues().next())
next(pixmap.loadFromData(self.load_resources(['images/icon.png']).itervalues())
icon = QIcon(pixmap)
:param names: List of paths to resources in the ZIP file using / as separator

View File

@ -46,7 +46,7 @@ from calibre.db.tables import (OneToOneTable, ManyToOneTable, ManyToManyTable,
Differences in semantics from pysqlite:
1. execute/executemany operate in autocommit mode
2. There is no fetchone() method on cursor objects, instead use next()
2. There is no fetchone() method on cursor objects, instead use next(cursor)
3. There is no executescript
'''
@ -120,7 +120,7 @@ class DBPrefs(dict): # {{{
raw = self.to_raw(val)
with self.db.conn:
try:
dbraw = self.db.execute('SELECT id,val FROM preferences WHERE key=?', (key,)).next()
dbraw = next(self.db.execute('SELECT id,val FROM preferences WHERE key=?', (key,)))
except StopIteration:
dbraw = None
if dbraw is None or dbraw[1] != raw:
@ -271,7 +271,7 @@ class Connection(apsw.Connection): # {{{
self.execute('pragma cache_size=-5000')
self.execute('pragma temp_store=2')
encoding = self.execute('pragma encoding').next()[0]
encoding = next(self.execute('pragma encoding'))[0]
self.createcollation('PYNOCASE', partial(pynocase,
encoding=encoding))
@ -306,7 +306,7 @@ class Connection(apsw.Connection): # {{{
if kw.get('all', True):
return ans.fetchall()
try:
return ans.next()[0]
return next(ans)[0]
except (StopIteration, IndexError):
return None
@ -875,7 +875,7 @@ class DB(object):
if kw.get('all', True):
return ans.fetchall()
try:
return ans.next()[0]
return next(ans)[0]
except (StopIteration, IndexError):
return None

View File

@ -24,7 +24,7 @@ class SchemaUpgrade(object):
# Upgrade database
try:
while True:
uv = self.db.execute('pragma user_version').next()[0]
uv = next(self.db.execute('pragma user_version'))[0]
meth = getattr(self, 'upgrade_version_%d'%uv, None)
if meth is None:
break

View File

@ -62,7 +62,7 @@ class Bookmark(): # {{{
kepub_chapter_data = ('{0}-%'.format(row[1]), )
cursor2.execute(kepub_chapter_query, kepub_chapter_data)
try:
kepub_chapter = cursor2.next()
kepub_chapter = next(cursor2)
chapter_title = kepub_chapter[0]
current_chapter = kepub_chapter[1]
except StopIteration:

View File

@ -185,7 +185,7 @@ class KOBO(USBMS):
cursor = connection.cursor()
cursor.execute('SELECT version FROM dbversion')
try:
result = cursor.next()
result = next(cursor)
dbversion = result['version']
except StopIteration:
dbversion = 0
@ -572,7 +572,7 @@ class KOBO(USBMS):
metadata = iter(metadata)
for i, location in enumerate(locations):
self.report_progress((i+1) / float(len(locations)), _('Adding books to device metadata listing...'))
info = metadata.next()
info = next(metadata)
debug_print("KoboTouch::add_books_to_metadata - info=%s" % info)
blist = 2 if location[1] == 'cardb' else 1 if location[1] == 'carda' else 0
@ -790,7 +790,7 @@ class KOBO(USBMS):
t = (ContentID,)
cursor.execute('select DateLastRead, ReadStatus from Content where BookID is Null and ContentID = ?', t)
try:
result = cursor.next()
result = next(cursor)
datelastread = result['DateLastRead']
current_ReadStatus = result['ReadStatus']
except StopIteration:
@ -1020,7 +1020,7 @@ class KOBO(USBMS):
t = (ContentID,)
cursor.execute('select ImageId from Content where BookID is Null and ContentID = ?', t)
try:
result = cursor.next()
result = next(cursor)
# debug_print("ImageId: ", result[0])
ImageID = result[0]
except StopIteration:
@ -2649,7 +2649,7 @@ class KOBOTOUCH(KOBO):
t = (ContentID,)
cursor.execute('select ImageId from Content where BookID is Null and ContentID = ?', t)
try:
result = cursor.next()
result = next(cursor)
ImageID = result[0]
except StopIteration:
ImageID = self.imageid_from_contentid(ContentID)
@ -2752,7 +2752,7 @@ class KOBOTOUCH(KOBO):
cursor = connection.cursor()
cursor.execute(test_query, test_values)
try:
result = cursor.next()
result = next(cursor)
except StopIteration:
result = None
@ -2860,7 +2860,7 @@ class KOBOTOUCH(KOBO):
cursor = connection.cursor()
cursor.execute(test_query, test_values)
try:
result = cursor.next()
result = next(cursor)
except StopIteration:
result = None
@ -2909,7 +2909,7 @@ class KOBOTOUCH(KOBO):
cursor = connection.cursor()
cursor.execute(test_query, test_values)
try:
result = cursor.next()
result = next(cursor)
except StopIteration:
result = None

View File

@ -705,8 +705,8 @@ class XMLCache(object):
child.text = '\n'+'\t'*(level+1)
for gc in child:
gc.tail = '\n'+'\t'*(level+1)
child.iterchildren(reversed=True).next().tail = '\n'+'\t'*level
root.iterchildren(reversed=True).next().tail = '\n'+'\t'*(level-1)
next(child.iterchildren(reversed=True)).tail = '\n'+'\t'*level
next(root.iterchildren(reversed=True)).tail = '\n'+'\t'*(level-1)
def move_playlists_to_bottom(self):
for root in self.record_roots.values():
@ -799,4 +799,3 @@ class XMLCache(object):
self.namespaces[i] = ns
# }}}

View File

@ -1471,7 +1471,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin):
metadata = iter(metadata)
for i, infile in enumerate(files):
mdata, fname = metadata.next(), names.next()
mdata, fname = next(metadata), next(names)
lpath = self._create_upload_path(mdata, fname, create_dirs=False)
self._debug('lpath', lpath)
if not hasattr(infile, 'read'):
@ -1497,7 +1497,7 @@ class SMART_DEVICE_APP(DeviceConfig, DevicePlugin):
for i, location in enumerate(locations):
self.report_progress((i + 1) / float(len(locations)),
_('Adding books to device metadata listing...'))
info = metadata.next()
info = next(metadata)
lpath = location[0]
length = location[1]
lpath = self._strip_prefix(lpath)

View File

@ -311,7 +311,7 @@ class USBMS(CLI, Device):
metadata = iter(metadata)
for i, infile in enumerate(files):
mdata, fname = metadata.next(), names.next()
mdata, fname = next(metadata), next(names)
filepath = self.normalize_path(self.create_upload_path(path, mdata, fname))
if not hasattr(infile, 'read'):
infile = self.normalize_path(infile)
@ -350,7 +350,7 @@ class USBMS(CLI, Device):
metadata = iter(metadata)
for i, location in enumerate(locations):
self.report_progress((i+1) / float(len(locations)), _('Adding books to device metadata listing...'))
info = metadata.next()
info = next(metadata)
blist = 2 if location[1] == 'cardb' else 1 if location[1] == 'carda' else 0
# Extract the correct prefix from the pathname. To do this correctly,

View File

@ -332,7 +332,7 @@ class PageElement:
g = generator()
while True:
try:
i = g.next()
i = next(g)
except StopIteration:
break
if i:

View File

@ -18,7 +18,7 @@ def decrypt_font_data(key, data, algorithm):
crypt_len = 1024 if is_adobe else 1040
crypt = bytearray(data[:crypt_len])
key = cycle(iter(bytearray(key)))
decrypt = bytes(bytearray(x^key.next() for x in crypt))
decrypt = bytes(bytearray(x^next(key) for x in crypt))
return decrypt + data[crypt_len:]

View File

@ -218,7 +218,7 @@ class EPUBOutput(OutputFormatPlugin):
if self.oeb.toc.count() == 0:
self.log.warn('This EPUB file has no Table of Contents. '
'Creating a default TOC')
first = iter(self.oeb.spine).next()
first = next(iter(self.oeb.spine))
self.oeb.toc.add(_('Start'), first.href)
from calibre.ebooks.oeb.base import OPF
@ -422,7 +422,7 @@ class EPUBOutput(OutputFormatPlugin):
if br.getparent() is None:
continue
try:
prior = br.itersiblings(preceding=True).next()
prior = next(br.itersiblings(preceding=True))
priortag = barename(prior.tag)
priortext = prior.tail
except:

View File

@ -125,10 +125,10 @@ class SNBOutput(OutputFormatPlugin):
if oeb_book.toc.count() == 0:
log.warn('This SNB file has no Table of Contents. '
'Creating a default TOC')
first = iter(oeb_book.spine).next()
first = next(iter(oeb_book.spine))
oeb_book.toc.add(_('Start page'), first.href)
else:
first = iter(oeb_book.spine).next()
first = next(iter(oeb_book.spine))
if oeb_book.toc[0].href != first.href:
# The pages before the fist item in toc will be stored as
# "Cover Pages".

View File

@ -32,7 +32,7 @@ def filter_name(name):
def build_name_for(expr):
if not expr:
counter = count(1)
return lambda elem: str(counter.next())
return lambda elem: str(next(counter))
selector = XPath(expr, namespaces=NSMAP)
def name_for(elem):
@ -55,7 +55,7 @@ def add_page_map(opfpath, opts):
name = name_for(elem)
id = elem.get('id', None)
if id is None:
id = elem.attrib['id'] = idgen.next()
id = elem.attrib['id'] = next(idgen)
href = '#'.join((item.href, id))
oeb.pages.add(name, href)
writer = None # DirWriter(version='2.0', page_map=True)

View File

@ -349,7 +349,7 @@ class Table(object):
nc = self.rows[r].cell_iterator()
try:
while True:
cell = nc.next()
cell = next(nc)
cellmatrix[r][rowpos[r]] = cell
rowpos[r] += cell.colspan
for k in range(1, cell.rowspan):

View File

@ -455,7 +455,7 @@ class Indexer(object): # {{{
self.is_periodical else 'book'))
self.is_flat_periodical = False
if self.is_periodical:
periodical_node = iter(oeb.toc).next()
periodical_node = next(iter(oeb.toc))
sections = tuple(periodical_node)
self.is_flat_periodical = len(sections) == 1
@ -681,7 +681,7 @@ class Indexer(object): # {{{
# }}}
def create_periodical_index(self): # {{{
periodical_node = iter(self.oeb.toc).next()
periodical_node = next(iter(self.oeb.toc))
periodical_node_offset = self.serializer.body_start_offset
periodical_node_size = (self.serializer.body_end_offset -
periodical_node_offset)

View File

@ -1782,7 +1782,7 @@ class PageList(object):
for page in self.pages:
id = page.id or uuid_id()
type = page.type
value = str(values[type].next())
value = str(next(values[type]))
attrib = {'id': id, 'value': value, 'type': type, 'playOrder': '0'}
if page.klass:
attrib['class'] = page.klass

View File

@ -98,7 +98,7 @@ def add_or_replace_jacket(container):
if not found:
# Insert new jacket into spine
index = 0
sp = container.abspath_to_name(container.spine_items.next())
sp = container.abspath_to_name(next(container.spine_items))
if sp == find_cover_page(container):
index = 1
itemref = container.opf.makeelement(OPF('itemref'),

View File

@ -243,7 +243,7 @@ class FlowSplitter(object):
self.trees = [orig_tree]
while ordered_ids:
pb_id, (pattern, before) = ordered_ids.iteritems().next()
pb_id, (pattern, before) = next(ordered_ids.iteritems())
del ordered_ids[pb_id]
for i in range(len(self.trees)-1, -1, -1):
tree = self.trees[i]

View File

@ -85,8 +85,8 @@ class DetectStructure(object):
for item in oeb.spine:
for elem in pb_xpath(item.data):
try:
prev = elem.itersiblings(tag=etree.Element,
preceding=True).next()
prev = next(elem.itersiblings(tag=etree.Element,
preceding=True))
if (barename(elem.tag) in {'h1', 'h2'} and barename(
prev.tag) in {'h1', 'h2'} and (not prev.tail or
not prev.tail.split())):

View File

@ -40,7 +40,7 @@ class Image(Element):
def __init__(self, img, opts, log, idc):
Element.__init__(self)
self.opts, self.log = opts, log
self.id = idc.next()
self.id = next(idc)
self.top, self.left, self.width, self.height, self.iwidth, self.iheight = \
map(float, map(img.get, ('top', 'left', 'rwidth', 'rheight', 'iwidth',
'iheight')))
@ -61,7 +61,7 @@ class Text(Element):
def __init__(self, text, font_map, opts, log, idc):
Element.__init__(self)
self.id = idc.next()
self.id = next(idc)
self.opts, self.log = opts, log
self.font_map = font_map
self.top, self.left, self.width, self.height = map(float, map(text.get,

View File

@ -278,7 +278,7 @@ class InterfaceAction(QObject):
For example to load an image::
pixmap = QPixmap()
pixmap.loadFromData(self.load_resources(['images/icon.png']).itervalues().next())
next(pixmap.loadFromData(self.load_resources(['images/icon.png']).itervalues()))
icon = QIcon(pixmap)
:param names: List of paths to resources in the ZIP file using / as separator

View File

@ -837,7 +837,7 @@ class BulkBase(Base):
break
ans = None
if len(values) == 1:
ans = iter(values).next()
ans = next(iter(values))
if isinstance(ans, frozenset):
ans = list(ans)
return ans

View File

@ -411,7 +411,7 @@ class DeviceManager(Thread): # {{{
do_sleep = True
while True:
job = self.next()
job = next(self)
if job is not None:
do_sleep = False
self.current_job = job
@ -1494,8 +1494,8 @@ class DeviceMixin(object): # {{{
bad, good, gf, names, remove_ids = [], [], [], [], []
for f in _files:
mi = imetadata.next()
id = ids.next()
mi = next(imetadata)
id = next(ids)
if f is None:
bad.append(mi.title)
else:

View File

@ -521,10 +521,9 @@ class Document(QGraphicsScene):
self.next_match()
def next_match(self):
page_num = self.last_search.next()[0]
page_num = next(self.last_search)[0]
if self.current_page == page_num:
self.update()
else:
self.add_to_history()
self.show_page(page_num)

View File

@ -532,12 +532,12 @@ class Line(QGraphicsItem):
matches = []
try:
while True:
word = words.next()
word = next(words)
word.highlight = False
if tokens[0] in unicode_type(word.string).lower():
matches.append(word)
for c in range(1, len(tokens)):
word = words.next()
word = next(words)
print(tokens[c], word.string)
if tokens[c] not in unicode_type(word.string):
return None

View File

@ -255,7 +255,7 @@ class CreateVirtualLibrary(QDialog): # {{{
search = ['%s:"=%s"'%(prefix, x.replace('"', '\\"')) for x in d.names]
if search:
if not self.editing:
self.vl_name.lineEdit().setText(d.names.next())
self.vl_name.lineEdit().setText(next(d.names))
self.vl_name.lineEdit().setCursorPosition(0)
self.vl_text.setText(d.match_type.join(search))
self.vl_text.setCursorPosition(0)

View File

@ -1337,10 +1337,10 @@ ALTER TABLE books ADD COLUMN isbn TEXT DEFAULT "" COLLATE NOCASE;
formats, metadata, uris = iter(formats), iter(metadata), iter(uris)
duplicates = []
for path in paths:
mi = metadata.next()
format = formats.next()
mi = next(metadata)
format = next(formats)
try:
uri = uris.next()
uri = next(uris)
except StopIteration:
uri = None
if not add_duplicates and self.has_book(mi):

View File

@ -3498,9 +3498,9 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
ids = []
postimport = []
for path in paths:
mi = metadata.next()
mi = next(metadata)
self._add_newbook_tag(mi)
format = formats.next()
format = next(formats)
if not add_duplicates and self.has_book(mi):
duplicates.append((path, format, mi))
continue

View File

@ -217,23 +217,23 @@ class NavBarTemplate(Template):
navbar.append(BR())
navbar.append(BR())
else:
next = 'feed_%d'%(feed+1) if art == number_of_articles_in_feed - 1 \
next_art = 'feed_%d'%(feed+1) if art == number_of_articles_in_feed - 1 \
else 'article_%d'%(art+1)
up = '../..' if art == number_of_articles_in_feed - 1 else '..'
href = '%s%s/%s/index.html'%(prefix, up, next)
href = '%s%s/%s/index.html'%(prefix, up, next_art)
navbar.text = '| '
navbar.append(A(_('Next'), href=href))
href = '%s../index.html#article_%d'%(prefix, art)
navbar.iterchildren(reversed=True).next().tail = ' | '
next(navbar.iterchildren(reversed=True)).tail = ' | '
navbar.append(A(_('Section menu'), href=href))
href = '%s../../index.html#feed_%d'%(prefix, feed)
navbar.iterchildren(reversed=True).next().tail = ' | '
next(navbar.iterchildren(reversed=True)).tail = ' | '
navbar.append(A(_('Main menu'), href=href))
if art > 0 and not bottom:
href = '%s../article_%d/index.html'%(prefix, art-1)
navbar.iterchildren(reversed=True).next().tail = ' | '
next(navbar.iterchildren(reversed=True)).tail = ' | '
navbar.append(A(_('Previous'), href=href))
navbar.iterchildren(reversed=True).next().tail = ' | '
next(navbar.iterchildren(reversed=True)).tail = ' | '
if not bottom:
navbar.append(HR())
@ -413,11 +413,11 @@ class TouchscreenNavBarTemplate(Template):
navbar_tr.append(TD(CLASS('article_sections_list'),link))
# | Next
next = 'feed_%d'%(feed+1) if art == number_of_articles_in_feed - 1 \
next_art = 'feed_%d'%(feed+1) if art == number_of_articles_in_feed - 1 \
else 'article_%d'%(art+1)
up = '../..' if art == number_of_articles_in_feed - 1 else '..'
link = A(CLASS('article_link'), _('Next'), href='%s%s/%s/index.html'%(prefix, up, next))
link = A(CLASS('article_link'), _('Next'), href='%s%s/%s/index.html'%(prefix, up, next_art))
navbar_tr.append(TD(CLASS('article_next'),link))
navbar_t.append(navbar_tr)
navbar.append(navbar_t)