py3: port use of isinstance(str)

This commit is contained in:
Kovid Goyal 2019-04-01 15:14:44 +05:30
parent 02ff98d8dc
commit 305a1bab29
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
14 changed files with 23 additions and 23 deletions

View File

@ -220,7 +220,7 @@ def prints(*args, **kwargs):
if not safe_encode: if not safe_encode:
raise raise
arg = repr(arg) arg = repr(arg)
if not isinstance(arg, str): if not isinstance(arg, bytes):
try: try:
arg = str(arg) arg = str(arg)
except ValueError: except ValueError:

View File

@ -203,7 +203,7 @@ class DateSearch(object): # {{{
field_count = query.count('/') + 1 field_count = query.count('/') + 1
for v, book_ids in field_iter(): for v, book_ids in field_iter():
if isinstance(v, (str, unicode_type)): if isinstance(v, string_or_bytes):
v = parse_date(v) v = parse_date(v)
if v is not None and relop(dt_as_local(v), qd, field_count): if v is not None and relop(dt_as_local(v), qd, field_count):
matches |= book_ids matches |= book_ids

View File

@ -10,7 +10,7 @@ import codecs
import os import os
from pylrfopt import tagListOptimizer from pylrfopt import tagListOptimizer
from polyglot.builtins import iteritems from polyglot.builtins import iteritems, string_or_bytes
PYLRF_VERSION = "1.0" PYLRF_VERSION = "1.0"
@ -130,7 +130,7 @@ def writeLineWidth(f, width):
def writeUnicode(f, string, encoding): def writeUnicode(f, string, encoding):
if isinstance(string, str): if isinstance(string, bytes):
string = string.decode(encoding) string = string.decode(encoding)
string = string.encode("utf-16-le") string = string.encode("utf-16-le")
length = len(string) length = len(string)
@ -141,7 +141,7 @@ def writeUnicode(f, string, encoding):
def writeRaw(f, string, encoding): def writeRaw(f, string, encoding):
if isinstance(string, str): if isinstance(string, bytes):
string = string.decode(encoding) string = string.decode(encoding)
string = string.encode("utf-16-le") string = string.encode("utf-16-le")
@ -398,7 +398,7 @@ class LrfTag(object):
for f in self.format: for f in self.format:
if isinstance(f, dict): if isinstance(f, dict):
p = f[p] p = f[p]
elif isinstance(f, str): elif isinstance(f, string_or_bytes):
if isinstance(p, tuple): if isinstance(p, tuple):
writeString(lrf, struct.pack(f, *p)) writeString(lrf, struct.pack(f, *p))
else: else:

View File

@ -1721,7 +1721,7 @@ class Text(LrsContainer):
def toLrfContainer(self, lrfWriter, parent): def toLrfContainer(self, lrfWriter, parent):
if self.text: if self.text:
if isinstance(self.text, str): if isinstance(self.text, bytes):
parent.appendLrfTag(LrfTag("rawtext", self.text)) parent.appendLrfTag(LrfTag("rawtext", self.text))
else: else:
parent.appendLrfTag(LrfTag("textstring", self.text)) parent.appendLrfTag(LrfTag("textstring", self.text))

View File

@ -217,7 +217,7 @@ class Resource(object):
path = href_or_path path = href_or_path
if not os.path.isabs(path): if not os.path.isabs(path):
path = os.path.abspath(os.path.join(basedir, path)) path = os.path.abspath(os.path.join(basedir, path))
if isinstance(path, str): if isinstance(path, bytes):
path = path.decode(sys.getfilesystemencoding()) path = path.decode(sys.getfilesystemencoding())
self.path = path self.path = path
else: else:

View File

@ -1079,7 +1079,7 @@ class Manifest(object):
return property(fget, fset, fdel, doc=doc) return property(fget, fset, fdel, doc=doc)
def unload_data_from_memory(self, memory=None): def unload_data_from_memory(self, memory=None):
if isinstance(self._data, (str, bytes)): if isinstance(self._data, bytes):
if memory is None: if memory is None:
from calibre.ptempfile import PersistentTemporaryFile from calibre.ptempfile import PersistentTemporaryFile
pt = PersistentTemporaryFile(suffix='_oeb_base_mem_unloader.img') pt = PersistentTemporaryFile(suffix='_oeb_base_mem_unloader.img')

View File

@ -248,7 +248,7 @@ class ParseRtf:
enc = 'cp' + enc enc = 'cp' + enc
msg = '%s\nException in token processing' % str(msg) msg = '%s\nException in token processing' % str(msg)
if check_encoding_obj.check_encoding(self.__file, enc): if check_encoding_obj.check_encoding(self.__file, enc):
file_name = self.__file if isinstance(self.__file, str) \ file_name = self.__file if isinstance(self.__file, bytes) \
else self.__file.encode('utf-8') else self.__file.encode('utf-8')
msg +='\nFile %s does not appear to be correctly encoded.\n' % file_name msg +='\nFile %s does not appear to be correctly encoded.\n' % file_name
try: try:

View File

@ -3508,9 +3508,9 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
if mi.series_index is None else mi.series_index if mi.series_index is None else mi.series_index
aus = mi.author_sort if mi.author_sort else self.author_sort_from_authors(mi.authors) aus = mi.author_sort if mi.author_sort else self.author_sort_from_authors(mi.authors)
title = mi.title title = mi.title
if isinstance(aus, str): if isinstance(aus, bytes):
aus = aus.decode(preferred_encoding, 'replace') aus = aus.decode(preferred_encoding, 'replace')
if isinstance(title, str): if isinstance(title, bytes):
title = title.decode(preferred_encoding) title = title.decode(preferred_encoding)
obj = self.conn.execute('INSERT INTO books(title, series_index, author_sort) VALUES (?, ?, ?)', obj = self.conn.execute('INSERT INTO books(title, series_index, author_sort) VALUES (?, ?, ?)',
(title, series_index, aus)) (title, series_index, aus))
@ -3552,7 +3552,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
if not mi.authors: if not mi.authors:
mi.authors = [_('Unknown')] mi.authors = [_('Unknown')]
aus = mi.author_sort if mi.author_sort else self.author_sort_from_authors(mi.authors) aus = mi.author_sort if mi.author_sort else self.author_sort_from_authors(mi.authors)
if isinstance(aus, str): if isinstance(aus, bytes):
aus = aus.decode(preferred_encoding, 'replace') aus = aus.decode(preferred_encoding, 'replace')
title = mi.title if isinstance(mi.title, unicode_type) else \ title = mi.title if isinstance(mi.title, unicode_type) else \
mi.title.decode(preferred_encoding, 'replace') mi.title.decode(preferred_encoding, 'replace')

View File

@ -1137,7 +1137,7 @@ class ServiceInfo(object):
value = properties[key] value = properties[key]
if value is None: if value is None:
suffix = '' suffix = ''
elif isinstance(value, str): elif isinstance(value, bytes):
suffix = value suffix = value
elif isinstance(value, numbers.Integral): elif isinstance(value, numbers.Integral):
suffix = value and 'true' or 'false' suffix = value and 'true' or 'false'

View File

@ -37,7 +37,7 @@ def prints(*args, **kwargs):
if not safe_encode: if not safe_encode:
raise raise
arg = repr(arg) arg = repr(arg)
if not isinstance(arg, str): if not isinstance(arg, bytes):
try: try:
arg = str(arg) arg = str(arg)
except ValueError: except ValueError:

View File

@ -22,6 +22,7 @@ from calibre.utils.config_base import (
tweaks, from_json, to_json tweaks, from_json, to_json
) )
from calibre.utils.lock import ExclusiveFile from calibre.utils.lock import ExclusiveFile
from polyglot.builtins import string_or_bytes
# optparse uses gettext.gettext instead of _ from builtins, so we # optparse uses gettext.gettext instead of _ from builtins, so we
@ -379,7 +380,7 @@ class XMLConfig(dict):
return self.defaults.get(key, default) return self.defaults.get(key, default)
def __setitem__(self, key, val): def __setitem__(self, key, val):
if isinstance(val, (bytes, str)): if isinstance(val, string_or_bytes):
val = plistlib.Data(val) val = plistlib.Data(val)
dict.__setitem__(self, key, val) dict.__setitem__(self, key, val)
self.commit() self.commit()

View File

@ -1104,7 +1104,7 @@ class BasicNewsRecipe(Recipe):
self.image_map[feed.image_url] = img self.image_map[feed.image_url] = img
except: except:
pass pass
if isinstance(feed.image_url, str): if isinstance(feed.image_url, bytes):
feed.image_url = feed.image_url.decode(sys.getfilesystemencoding(), 'strict') feed.image_url = feed.image_url.decode(sys.getfilesystemencoding(), 'strict')
templ = (templates.TouchscreenFeedTemplate if self.touchscreen else templ = (templates.TouchscreenFeedTemplate if self.touchscreen else

View File

@ -42,7 +42,7 @@ def serialize_recipe(urn, recipe_class):
def attr(n, d): def attr(n, d):
ans = getattr(recipe_class, n, d) ans = getattr(recipe_class, n, d)
if isinstance(ans, str): if isinstance(ans, bytes):
ans = ans.decode('utf-8', 'replace') ans = ans.decode('utf-8', 'replace')
return ans return ans
@ -66,7 +66,7 @@ def serialize_collection(mapping_of_recipe_classes):
collection = E.recipe_collection() collection = E.recipe_collection()
'''for u, x in mapping_of_recipe_classes.items(): '''for u, x in mapping_of_recipe_classes.items():
print 11111, u, repr(x.title) print 11111, u, repr(x.title)
if isinstance(x.title, str): if isinstance(x.title, bytes):
x.title.decode('ascii') x.title.decode('ascii')
''' '''
for urn in sorted(mapping_of_recipe_classes.keys(), for urn in sorted(mapping_of_recipe_classes.keys(),

View File

@ -7,9 +7,11 @@ __license__ = 'GPL v3'
__copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>'
import collections import collections
from polyglot.builtins import string_or_bytes
SLICE_ALL = slice(None) SLICE_ALL = slice(None)
def is_iterable(obj): def is_iterable(obj):
""" """
Are we being asked to look up a list of things, instead of a single thing? Are we being asked to look up a list of things, instead of a single thing?
@ -18,11 +20,8 @@ def is_iterable(obj):
Strings, however, should be considered as atomic values to look up, not Strings, however, should be considered as atomic values to look up, not
iterables. iterables.
We don't need to check for the Python 2 `unicode` type, because it doesn't
have an `__iter__` attribute anyway.
""" """
return hasattr(obj, '__iter__') and not isinstance(obj, str) return hasattr(obj, '__iter__') and not isinstance(obj, string_or_bytes)
class OrderedSet(collections.MutableSet): class OrderedSet(collections.MutableSet):