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 @@ def load_resources(self, names):
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 @@
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 @@ def __setitem__(self, key, val):
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 @@ def __init__(self, path):
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 @@ def get(self, *args, **kw):
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 @@ def get(self, *args, **kw):
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 @@ def __init__(self, db, library_path, field_metadata):
# 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 @@ def get_bookmark_data(self):
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 @@ def get_database_version(self, connection):
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 @@ def add_books_to_metadata(self, locations, metadata, booklists):
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 @@ def set_readstatus(self, connection, ContentID, ReadStatus):
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 @@ def _upload_cover(self, path, filename, metadata, filepath, uploadgrayscale):
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 @@ def _upload_cover(self, path, filename, metadata, filepath, upload_grayscale, ke
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 @@ def set_filesize_in_device_database(self, connection, contentID, fpath):
cursor = connection.cursor()
cursor.execute(test_query, test_values)
try:
result = cursor.next()
result = next(cursor)
except StopIteration:
result = None
@ -2860,7 +2860,7 @@ def set_bookshelf(self, connection, book, shelfName):
cursor = connection.cursor()
cursor.execute(test_query, test_values)
try:
result = cursor.next()
result = next(cursor)
except StopIteration:
result = None
@ -2909,7 +2909,7 @@ def check_for_bookshelf(self, connection, bookshelf_name):
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 @@ def cleanup_whitespace(self, bl_index):
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 @@ def detect_namespaces(self):
self.namespaces[i] = ns
# }}}

View file

@ -1471,7 +1471,7 @@ def upload_books(self, files, names, on_card=None, end_session=True,
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 @@ def add_books_to_metadata(self, locations, metadata, booklists):
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 @@ def upload_books(self, files, names, on_card=None, end_session=True,
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 @@ def add_books_to_metadata(self, locations, metadata, booklists):
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 @@ def _findAll(self, name, attrs, text, limit, generator, **kwargs):
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 @@ def convert(self, oeb, output_path, input_plugin, opts, log):
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 @@ def workaround_ade_quirks(self): # {{{
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 @@ def convert(self, oeb_book, output_path, input_plugin, opts, log):
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 @@ def blocks(self, maxwidth, maxheight):
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 @@ def __init__(self, serializer, number_of_text_records,
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 @@ def create_book_index(self): # {{{
# }}}
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 @@ def to_ncx(self, parent=None):
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 @@ def split_on_page_breaks(self, orig_tree):
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 @@ def __call__(self, oeb, opts):
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 @@ def load_resources(self, names):
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 @@ def get_initial_value(self, book_ids):
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 @@ def run(self):
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 @@ def sync_to_device(self, on_card, delete_from_library,
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 @@ def search(self, phrase):
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 @@ def search(self, phrase):
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 @@ def link_activated(self, url):
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 @@ def add_books(self, paths, formats, metadata, uris=[], add_duplicates=True):
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 @@ def add_books(self, paths, formats, metadata, add_duplicates=True,
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 @@ def _generate(self, bottom, feed, art, number_of_articles_in_feed,
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 @@ def _generate(self, bottom, feed, art, number_of_articles_in_feed,
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)