Use ABC to test for numbers type

This is important as long does not exist on py3 and anyway using an ABC
is more robust.  Also fix a few uses of long() for py3.
This commit is contained in:
Kovid Goyal 2019-03-16 12:17:14 +05:30
parent 8921bb8324
commit dc274d8c1c
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
59 changed files with 154 additions and 135 deletions

View File

@ -2,7 +2,7 @@
''' '''
Defines the plugin system for conversions. Defines the plugin system for conversions.
''' '''
import re, os, shutil import re, os, shutil, numbers
from calibre import CurrentDir from calibre import CurrentDir
from calibre.customize import Plugin from calibre.customize import Plugin
@ -80,7 +80,7 @@ class OptionRecommendation(object):
self.option.choices: self.option.choices:
raise ValueError('OpRec: %s: Recommended value not in choices'% raise ValueError('OpRec: %s: Recommended value not in choices'%
self.option.name) self.option.name)
if not (isinstance(self.recommended_value, (int, float, str, unicode_type)) or self.recommended_value is None): if not (isinstance(self.recommended_value, (numbers.Number, bytes, unicode_type)) or self.recommended_value is None):
raise ValueError('OpRec: %s:'%self.option.name + repr( raise ValueError('OpRec: %s:'%self.option.name + repr(
self.recommended_value) + ' is not a string or a number') self.recommended_value) + ' is not a string or a number')

View File

@ -9,6 +9,7 @@ __docformat__ = 'restructuredtext en'
SPOOL_SIZE = 30*1024*1024 SPOOL_SIZE = 30*1024*1024
import numbers
from polyglot.builtins import range from polyglot.builtins import range
@ -16,7 +17,7 @@ def _get_next_series_num_for_list(series_indices, unwrap=True):
from calibre.utils.config_base import tweaks from calibre.utils.config_base import tweaks
from math import ceil, floor from math import ceil, floor
if not series_indices: if not series_indices:
if isinstance(tweaks['series_index_auto_increment'], (int, float)): if isinstance(tweaks['series_index_auto_increment'], numbers.Number):
return float(tweaks['series_index_auto_increment']) return float(tweaks['series_index_auto_increment'])
return 1.0 return 1.0
if unwrap: if unwrap:
@ -38,7 +39,7 @@ def _get_next_series_num_for_list(series_indices, unwrap=True):
if i not in series_indices: if i not in series_indices:
return i return i
return series_indices[-1] + 1 return series_indices[-1] + 1
if isinstance(tweaks['series_index_auto_increment'], (int, float)): if isinstance(tweaks['series_index_auto_increment'], numbers.Number):
return float(tweaks['series_index_auto_increment']) return float(tweaks['series_index_auto_increment'])
return 1.0 return 1.0

View File

@ -7,6 +7,7 @@ __license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import numbers
from datetime import datetime, timedelta from datetime import datetime, timedelta
from collections import defaultdict from collections import defaultdict
@ -24,7 +25,7 @@ def c_parse(val):
except (AttributeError, TypeError): except (AttributeError, TypeError):
# If a value like 2001 is stored in the column, apsw will return it as # If a value like 2001 is stored in the column, apsw will return it as
# an int # an int
if isinstance(val, (int, float)): if isinstance(val, numbers.Number):
return datetime(int(val), 1, 3, tzinfo=utc_tz) return datetime(int(val), 1, 3, tzinfo=utc_tz)
if val is None: if val is None:
return UNDEFINED_DATE return UNDEFINED_DATE

View File

@ -6,7 +6,7 @@ from __future__ import (unicode_literals, division, absolute_import,
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import inspect, time import inspect, time, numbers
from io import BytesIO from io import BytesIO
from repr import repr from repr import repr
from functools import partial from functools import partial
@ -109,7 +109,7 @@ class LegacyTest(BaseTest):
def get_values(db): def get_values(db):
ans = {} ans = {}
for label, loc in db.FIELD_MAP.iteritems(): for label, loc in db.FIELD_MAP.iteritems():
if isinstance(label, int): if isinstance(label, numbers.Integral):
label = '#'+db.custom_column_num_map[label]['label'] label = '#'+db.custom_column_num_map[label]['label']
label = type('')(label) label = type('')(label)
ans[label] = tuple(db.get_property(i, index_is_id=True, loc=loc) ans[label] = tuple(db.get_property(i, index_is_id=True, loc=loc)

View File

@ -7,7 +7,7 @@ __license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import weakref, operator import weakref, operator, numbers
from functools import partial from functools import partial
from itertools import izip, imap from itertools import izip, imap
from polyglot.builtins import map, unicode_type, range from polyglot.builtins import map, unicode_type, range
@ -98,7 +98,7 @@ class View(object):
'marked': self.get_marked, 'marked': self.get_marked,
'series_sort':self.get_series_sort, 'series_sort':self.get_series_sort,
}.get(col, self._get) }.get(col, self._get)
if isinstance(col, int): if isinstance(col, numbers.Integral):
label = self.cache.backend.custom_column_num_map[col]['label'] label = self.cache.backend.custom_column_num_map[col]['label']
label = (self.cache.backend.field_metadata.custom_field_prefix + label) label = (self.cache.backend.field_metadata.custom_field_prefix + label)
if label.endswith('_index'): if label.endswith('_index'):

View File

@ -24,7 +24,7 @@ from calibre.devices.usbms.books import CollectionsBookList
from calibre.devices.usbms.books import BookList from calibre.devices.usbms.books import BookList
from calibre.ebooks.metadata import authors_to_sort_string, authors_to_string from calibre.ebooks.metadata import authors_to_sort_string, authors_to_string
from calibre.constants import islinux from calibre.constants import islinux
from polyglot.builtins import unicode_type from polyglot.builtins import unicode_type, long_type
DBPATH = 'Sony_Reader/database/books.db' DBPATH = 'Sony_Reader/database/books.db'
THUMBPATH = 'Sony_Reader/database/cache/books/%s/thumbnail/main_thumbnail.jpg' THUMBPATH = 'Sony_Reader/database/cache/books/%s/thumbnail/main_thumbnail.jpg'
@ -330,7 +330,7 @@ class PRST1(USBMS):
cursor.execute(query) cursor.execute(query)
row = cursor.fetchone() row = cursor.fetchone()
return long(row[0]) return long_type(row[0])
def get_database_min_id(self, source_id): def get_database_min_id(self, source_id):
sequence_min = 0 sequence_min = 0

View File

@ -7,7 +7,7 @@ Code for the conversion of ebook formats and the reading of metadata
from various formats. from various formats.
''' '''
import traceback, os, re import traceback, os, re, numbers
from calibre import CurrentDir, prints from calibre import CurrentDir, prints
from polyglot.builtins import unicode_type from polyglot.builtins import unicode_type
@ -233,7 +233,7 @@ UNIT_RE = re.compile(r'^(-*[0-9]*[.]?[0-9]*)\s*(%|em|ex|en|px|mm|cm|in|pt|pc|rem
def unit_convert(value, base, font, dpi, body_font_size=12): def unit_convert(value, base, font, dpi, body_font_size=12):
' Return value in pts' ' Return value in pts'
if isinstance(value, (int, long, float)): if isinstance(value, numbers.Number):
return value return value
try: try:
return float(value) * 72.0 / dpi return float(value) * 72.0 / dpi

View File

@ -7,7 +7,7 @@ __docformat__ = 'restructuredtext en'
Command line interface to conversion sub-system Command line interface to conversion sub-system
''' '''
import sys, os import sys, os, numbers
from optparse import OptionGroup, Option from optparse import OptionGroup, Option
from collections import OrderedDict from collections import OrderedDict
@ -91,9 +91,9 @@ def option_recommendation_to_cli_option(add_option, rec):
attrs['action'] = 'store_false' if rec.recommended_value else \ attrs['action'] = 'store_false' if rec.recommended_value else \
'store_true' 'store_true'
else: else:
if isinstance(rec.recommended_value, int): if isinstance(rec.recommended_value, numbers.Integral):
attrs['type'] = 'int' attrs['type'] = 'int'
if isinstance(rec.recommended_value, float): if isinstance(rec.recommended_value, numbers.Real):
attrs['type'] = 'float' attrs['type'] = 'float'
if opt.long_switch == 'verbose': if opt.long_switch == 'verbose':

View File

@ -6,7 +6,7 @@ from __future__ import (unicode_literals, division, absolute_import,
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>'
import re, random, unicodedata import re, random, unicodedata, numbers
from collections import namedtuple from collections import namedtuple
from contextlib import contextmanager from contextlib import contextmanager
from math import ceil, sqrt, cos, sin, atan2 from math import ceil, sqrt, cos, sin, atan2
@ -167,7 +167,7 @@ class Block(object):
@property @property
def height(self): def height(self):
return int(ceil(sum(l if isinstance(l, (int, float)) else l.boundingRect().height() for l in self.layouts))) return int(ceil(sum(l if isinstance(l, numbers.Number) else l.boundingRect().height() for l in self.layouts)))
@dynamic_property @dynamic_property
def position(self): def position(self):
@ -181,7 +181,7 @@ class Block(object):
self.layouts[0].setPosition(QPointF(x, y)) self.layouts[0].setPosition(QPointF(x, y))
y += self.layouts[0].boundingRect().height() y += self.layouts[0].boundingRect().height()
for l in self.layouts[1:]: for l in self.layouts[1:]:
if isinstance(l, (int, float)): if isinstance(l, numbers.Number):
y += l y += l
else: else:
l.setPosition(QPointF(x, y)) l.setPosition(QPointF(x, y))

View File

@ -6,7 +6,7 @@ from __future__ import (unicode_literals, division, absolute_import,
print_function) print_function)
from functools import partial from functools import partial
from collections import OrderedDict from collections import OrderedDict
import operator import operator, numbers
from css_parser.css import Property, CSSRule from css_parser.css import Property, CSSRule
@ -123,7 +123,7 @@ def unit_convert(value, unit, dpi=96.0, body_font_size=12):
def parse_css_length_or_number(raw, default_unit=None): def parse_css_length_or_number(raw, default_unit=None):
if isinstance(raw, (int, long, float)): if isinstance(raw, numbers.Number):
return raw, default_unit return raw, default_unit
try: try:
return float(raw), default_unit return float(raw), default_unit

View File

@ -6,6 +6,7 @@ from __future__ import (unicode_literals, division, absolute_import,
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import numbers
from collections import OrderedDict from collections import OrderedDict
@ -126,7 +127,7 @@ def border_to_css(edge, style, css):
bs = getattr(style, 'border_%s_style' % edge) bs = getattr(style, 'border_%s_style' % edge)
bc = getattr(style, 'border_%s_color' % edge) bc = getattr(style, 'border_%s_color' % edge)
bw = getattr(style, 'border_%s_width' % edge) bw = getattr(style, 'border_%s_width' % edge)
if isinstance(bw, (float, int, long)): if isinstance(bw, numbers.Number):
# WebKit needs at least 1pt to render borders and 3pt to render double borders # WebKit needs at least 1pt to render borders and 3pt to render double borders
bw = max(bw, (3 if bs == 'double' else 1)) bw = max(bw, (3 if bs == 'double' else 1))
if bs is not inherit and bs is not None: if bs is not inherit and bs is not None:
@ -134,7 +135,7 @@ def border_to_css(edge, style, css):
if bc is not inherit and bc is not None: if bc is not inherit and bc is not None:
css['border-%s-color' % edge] = bc css['border-%s-color' % edge] = bc
if bw is not inherit and bw is not None: if bw is not inherit and bw is not None:
if isinstance(bw, (int, float, long)): if isinstance(bw, numbers.Number):
bw = '%.3gpt' % bw bw = '%.3gpt' % bw
css['border-%s-width' % edge] = bw css['border-%s-width' % edge] = bw

View File

@ -6,6 +6,7 @@ from __future__ import (unicode_literals, division, absolute_import,
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>'
import numbers
from collections import Counter, defaultdict from collections import Counter, defaultdict
from operator import attrgetter from operator import attrgetter
@ -232,7 +233,7 @@ class TextStyle(DOCXStyle):
except (ValueError, TypeError, AttributeError): except (ValueError, TypeError, AttributeError):
self.spacing = None self.spacing = None
va = css.first_vertical_align va = css.first_vertical_align
if isinstance(va, (int, float)): if isinstance(va, numbers.Number):
self.vertical_align = str(int(va * 2)) self.vertical_align = str(int(va * 2))
else: else:
val = { val = {
@ -254,7 +255,7 @@ class TextStyle(DOCXStyle):
elif self.padding != padding: elif self.padding != padding:
self.padding = ignore self.padding = ignore
val = css['border-%s-width' % edge] val = css['border-%s-width' % edge]
if not isinstance(val, (float, int, long)): if not isinstance(val, numbers.Number):
val = {'thin':0.2, 'medium':1, 'thick':2}.get(val, 0) val = {'thin':0.2, 'medium':1, 'thick':2}.get(val, 0)
val = min(96, max(2, int(val * 8))) val = min(96, max(2, int(val * 8)))
if self.border_width is None: if self.border_width is None:
@ -467,7 +468,7 @@ def read_css_block_borders(self, css, store_css_style=False):
setattr(self, 'margin_' + edge, 0) # for e.g.: margin: auto setattr(self, 'margin_' + edge, 0) # for e.g.: margin: auto
setattr(self, 'css_margin_' + edge, css._style.get('margin-' + edge, '')) setattr(self, 'css_margin_' + edge, css._style.get('margin-' + edge, ''))
val = css['border-%s-width' % edge] val = css['border-%s-width' % edge]
if not isinstance(val, (float, int, long)): if not isinstance(val, numbers.Number):
val = {'thin':0.2, 'medium':1, 'thick':2}.get(val, 0) val = {'thin':0.2, 'medium':1, 'thick':2}.get(val, 0)
val = min(96, max(2, int(val * 8))) val = min(96, max(2, int(val * 8)))
setattr(self, 'border_%s_width' % edge, val) setattr(self, 'border_%s_width' % edge, val)

View File

@ -6,7 +6,7 @@ from __future__ import (unicode_literals, division, absolute_import,
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>'
import unittest import unittest, numbers
from polyglot.builtins import map from polyglot.builtins import map
from calibre.ebooks.epub.cfi.parse import parser, cfi_sort_key, decode_cfi from calibre.ebooks.epub.cfi.parse import parser, cfi_sort_key, decode_cfi
@ -29,7 +29,7 @@ class Tests(unittest.TestCase):
p = parser() p = parser()
def step(x): def step(x):
if isinstance(x, int): if isinstance(x, numbers.Integral):
return {'num': x} return {'num': x}
return {'num':x[0], 'id':x[1]} return {'num':x[0], 'id':x[1]}

View File

@ -9,7 +9,7 @@ __license__ = 'GPL v3'
__copyright__ = '2008, Marshall T. Vandegrift <llasram@gmail.com>' __copyright__ = '2008, Marshall T. Vandegrift <llasram@gmail.com>'
import struct, copy import struct, copy
from polyglot.builtins import range from polyglot.builtins import range, long_type
# ====================================================================== # ======================================================================
# Bit-Manipulation helpers # Bit-Manipulation helpers
@ -62,10 +62,10 @@ def _bytelist2longBigEndian(list):
j = 0 j = 0
i = 0 i = 0
while i < imax: while i < imax:
b0 = long(ord(list[j])) << 24 b0 = long_type(ord(list[j])) << 24
b1 = long(ord(list[j+1])) << 16 b1 = long_type(ord(list[j+1])) << 16
b2 = long(ord(list[j+2])) << 8 b2 = long_type(ord(list[j+2])) << 8
b3 = long(ord(list[j+3])) b3 = long_type(ord(list[j+3]))
hl[i] = b0 | b1 | b2 | b3 hl[i] = b0 | b1 | b2 | b3
i = i+1 i = i+1
j = j+4 j = j+4
@ -204,7 +204,7 @@ class mssha1(object):
to the hashed string. to the hashed string.
""" """
leninBuf = long(len(inBuf)) leninBuf = long_type(len(inBuf))
# Compute number of bytes mod 64. # Compute number of bytes mod 64.
index = (self.count[1] >> 3) & 0x3F index = (self.count[1] >> 3) & 0x3F

View File

@ -16,6 +16,7 @@ import re
import copy import copy
import uuid import uuid
import functools import functools
import numbers
from urlparse import urldefrag from urlparse import urldefrag
from urllib import unquote as urlunquote from urllib import unquote as urlunquote
from lxml import etree from lxml import etree
@ -162,7 +163,7 @@ class ReBinary(object):
def write(self, *values): def write(self, *values):
for value in values: for value in values:
if isinstance(value, (int, long)): if isinstance(value, numbers.Integral):
try: try:
value = codepoint_to_chr(value) value = codepoint_to_chr(value)
except OverflowError: except OverflowError:

View File

@ -1,7 +1,7 @@
from __future__ import print_function from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
import math, sys, re import math, sys, re, numbers
from calibre.ebooks.lrf.fonts import get_font from calibre.ebooks.lrf.fonts import get_font
from calibre.ebooks.lrf.pylrs.pylrs import TextBlock, Text, CR, Span, \ from calibre.ebooks.lrf.pylrs.pylrs import TextBlock, Text, CR, Span, \
@ -137,7 +137,7 @@ class Cell(object):
mwidth = 0 mwidth = 0
for token, attrs in tokens(tb): for token, attrs in tokens(tb):
font = default_font font = default_font
if isinstance(token, int): # Handle para and line breaks if isinstance(token, numbers.Integral): # Handle para and line breaks
continue continue
if isinstance(token, Plot): if isinstance(token, Plot):
return self.pts_to_pixels(token.xsize) return self.pts_to_pixels(token.xsize)
@ -178,7 +178,7 @@ class Cell(object):
ls = self.pts_to_pixels(attrs.get('baselineskip', ts['baselineskip']))+\ ls = self.pts_to_pixels(attrs.get('baselineskip', ts['baselineskip']))+\
self.pts_to_pixels(attrs.get('linespace', ts['linespace'])) self.pts_to_pixels(attrs.get('linespace', ts['linespace']))
ws = self.pts_to_pixels(attrs.get('wordspace', ts['wordspace'])) ws = self.pts_to_pixels(attrs.get('wordspace', ts['wordspace']))
if isinstance(token, int): # Handle para and line breaks if isinstance(token, numbers.Integral): # Handle para and line breaks
if top != bottom: # Previous element not a line break if top != bottom: # Previous element not a line break
top = bottom top = bottom
else: else:

View File

@ -10,7 +10,7 @@ __copyright__ = '2009, Kovid Goyal kovid@kovidgoyal.net and ' \
'Marshall T. Vandegrift <llasram@gmail.com>' 'Marshall T. Vandegrift <llasram@gmail.com>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import os import os, numbers
from struct import pack, unpack from struct import pack, unpack
from cStringIO import StringIO from cStringIO import StringIO
@ -47,7 +47,7 @@ class StreamSlicer(object):
def __getitem__(self, key): def __getitem__(self, key):
stream = self._stream stream = self._stream
base = self.start base = self.start
if isinstance(key, (int, long)): if isinstance(key, numbers.Integral):
stream.seek(base + key) stream.seek(base + key)
return stream.read(1) return stream.read(1)
if isinstance(key, slice): if isinstance(key, slice):
@ -67,7 +67,7 @@ class StreamSlicer(object):
def __setitem__(self, key, value): def __setitem__(self, key, value):
stream = self._stream stream = self._stream
base = self.start base = self.start
if isinstance(key, (int, long)): if isinstance(key, numbers.Integral):
if len(value) != 1: if len(value) != 1:
raise ValueError("key and value lengths must match") raise ValueError("key and value lengths must match")
stream.seek(base + key) stream.seek(base + key)

View File

@ -5,7 +5,7 @@ __copyright__ = '2010, Greg Riker <griker@hotmail.com>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
''' Read/write metadata from Amazon's topaz format ''' ''' Read/write metadata from Amazon's topaz format '''
import StringIO, sys import StringIO, sys, numbers
from struct import pack from struct import pack
from calibre.ebooks.metadata import MetaInformation from calibre.ebooks.metadata import MetaInformation
@ -29,7 +29,7 @@ class StreamSlicer(object):
def __getitem__(self, key): def __getitem__(self, key):
stream = self._stream stream = self._stream
base = self.start base = self.start
if isinstance(key, (int, long)): if isinstance(key, numbers.Integral):
stream.seek(base + key) stream.seek(base + key)
return stream.read(1) return stream.read(1)
if isinstance(key, slice): if isinstance(key, slice):
@ -49,7 +49,7 @@ class StreamSlicer(object):
def __setitem__(self, key, value): def __setitem__(self, key, value):
stream = self._stream stream = self._stream
base = self.start base = self.start
if isinstance(key, (int, long)): if isinstance(key, numbers.Integral):
if len(value) != 1: if len(value) != 1:
raise ValueError("key and value lengths must match") raise ValueError("key and value lengths must match")
stream.seek(base + key) stream.seek(base + key)

View File

@ -7,7 +7,7 @@ __license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2012, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import struct, datetime, os import struct, datetime, os, numbers
from calibre.utils.date import utc_tz from calibre.utils.date import utc_tz
from calibre.ebooks.mobi.reader.headers import NULL_INDEX from calibre.ebooks.mobi.reader.headers import NULL_INDEX
@ -598,7 +598,7 @@ class TextRecord(object): # {{{
self.trailing_data['raw_bytes'] = raw_trailing_bytes self.trailing_data['raw_bytes'] = raw_trailing_bytes
for typ, val in self.trailing_data.iteritems(): for typ, val in self.trailing_data.iteritems():
if isinstance(typ, int): if isinstance(typ, numbers.Integral):
print ('Record %d has unknown trailing data of type: %d : %r'% print ('Record %d has unknown trailing data of type: %d : %r'%
(idx, typ, val)) (idx, typ, val))

View File

@ -9,6 +9,7 @@ __copyright__ = '2008, Marshall T. Vandegrift <llasram@gmail.cam>'
import copy import copy
import re import re
import numbers
from lxml import etree from lxml import etree
from calibre.ebooks.oeb.base import namespace, barename from calibre.ebooks.oeb.base import namespace, barename
from calibre.ebooks.oeb.base import XHTML, XHTML_NS, urlnormalize from calibre.ebooks.oeb.base import XHTML, XHTML_NS, urlnormalize
@ -45,7 +46,7 @@ COLLAPSE = re.compile(r'[ \t\r\n\v]+')
def asfloat(value): def asfloat(value):
if not isinstance(value, (int, long, float)): if not isinstance(value, numbers.Number):
return 0.0 return 0.0
return float(value) return float(value)
@ -531,9 +532,9 @@ class MobiMLizer(object):
valign = style['vertical-align'] valign = style['vertical-align']
not_baseline = valign in ('super', 'sub', 'text-top', not_baseline = valign in ('super', 'sub', 'text-top',
'text-bottom', 'top', 'bottom') or ( 'text-bottom', 'top', 'bottom') or (
isinstance(valign, (float, int)) and abs(valign) != 0) isinstance(valign, numbers.Number) and abs(valign) != 0)
issup = valign in ('super', 'text-top', 'top') or ( issup = valign in ('super', 'text-top', 'top') or (
isinstance(valign, (float, int)) and valign > 0) isinstance(valign, numbers.Number) and valign > 0)
vtag = 'sup' if issup else 'sub' vtag = 'sup' if issup else 'sub'
if not_baseline and not ignore_valign and tag not in NOT_VTAGS and not isblock: if not_baseline and not ignore_valign and tag not in NOT_VTAGS and not isblock:
nroot = etree.Element(XHTML('html'), nsmap=MOBI_NSMAP) nroot = etree.Element(XHTML('html'), nsmap=MOBI_NSMAP)

View File

@ -8,6 +8,7 @@ __license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import numbers
from struct import pack from struct import pack
from cStringIO import StringIO from cStringIO import StringIO
from collections import OrderedDict, defaultdict from collections import OrderedDict, defaultdict
@ -166,7 +167,7 @@ class IndexEntry(object):
@property @property
def bytestring(self): def bytestring(self):
buf = StringIO() buf = StringIO()
if isinstance(self.index, int): if isinstance(self.index, numbers.Integral):
buf.write(encode_number_as_hex(self.index)) buf.write(encode_number_as_hex(self.index))
else: else:
raw = bytearray(self.index.encode('ascii')) raw = bytearray(self.index.encode('ascii'))
@ -188,7 +189,7 @@ class IndexEntry(object):
for tag in self.tag_nums: for tag in self.tag_nums:
attr = self.attr_for_tag(tag) attr = self.attr_for_tag(tag)
val = getattr(self, attr) val = getattr(self, attr)
if isinstance(val, int): if isinstance(val, numbers.Integral):
val = [val] val = [val]
for x in val: for x in val:
buf.write(encint(x)) buf.write(encint(x))
@ -602,7 +603,7 @@ class Indexer(object): # {{{
# The index of the last entry in the NCX # The index of the last entry in the NCX
idx = indices[-1].index idx = indices[-1].index
if isinstance(idx, int): if isinstance(idx, numbers.Integral):
idx = encode_number_as_hex(idx) idx = encode_number_as_hex(idx)
else: else:
idx = idx.encode('ascii') idx = idx.encode('ascii')

View File

@ -7,7 +7,7 @@ __license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2012, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import random import random, numbers
from io import BytesIO from io import BytesIO
from collections import OrderedDict from collections import OrderedDict
from struct import pack from struct import pack
@ -67,7 +67,7 @@ class Header(OrderedDict):
positions[name] = buf.tell() positions[name] = buf.tell()
if val is None: if val is None:
raise ValueError('Dynamic field %r not set'%name) raise ValueError('Dynamic field %r not set'%name)
if isinstance(val, (int, long)): if isinstance(val, numbers.Integral):
fmt = b'H' if name in self.SHORT_FIELDS else b'I' fmt = b'H' if name in self.SHORT_FIELDS else b'I'
val = pack(b'>'+fmt, val) val = pack(b'>'+fmt, val)
buf.write(val) buf.write(val)
@ -83,6 +83,3 @@ class Header(OrderedDict):
def format_value(self, name, val): def format_value(self, name, val):
return val return val

View File

@ -7,7 +7,7 @@ __license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2012, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import os import os, numbers
from io import BytesIO from io import BytesIO
from calibre.utils.zipfile import safe_replace from calibre.utils.zipfile import safe_replace
@ -59,7 +59,7 @@ class BookmarksMixin(object):
rec = u'%s^%d#%s'%(bm['title'], bm['spine'], bm['pos']) rec = u'%s^%d#%s'%(bm['title'], bm['spine'], bm['pos'])
else: else:
pos = bm['pos'] pos = bm['pos']
if isinstance(pos, (int, float)): if isinstance(pos, numbers.Number):
pos = unicode_type(pos) pos = unicode_type(pos)
else: else:
pos = pos.replace(u'^', BM_LEGACY_ESC) pos = pos.replace(u'^', BM_LEGACY_ESC)

View File

@ -6,6 +6,7 @@ from __future__ import (unicode_literals, division, absolute_import,
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import numbers
from polyglot.builtins import zip, string_or_bytes from polyglot.builtins import zip, string_or_bytes
from functools import wraps from functools import wraps
@ -392,7 +393,7 @@ def test_normalization(return_tests=False): # {{{
tuple('0 0 0 0'.split()) : '0', tuple('0 0 0 0'.split()) : '0',
}.iteritems(): }.iteritems():
for prefix in ('margin', 'padding'): for prefix in ('margin', 'padding'):
css = {'%s-%s' % (prefix, x) : str(y)+'pt' if isinstance(y, (int, float)) else y for x, y in zip(('left', 'top', 'right', 'bottom'), s)} css = {'%s-%s' % (prefix, x) : str(y)+'pt' if isinstance(y, numbers.Number) else y for x, y in zip(('left', 'top', 'right', 'bottom'), s)}
css = '; '.join(('%s:%s' % (k, v) for k, v in css.iteritems())) css = '; '.join(('%s:%s' % (k, v) for k, v in css.iteritems()))
style = parseStyle(css) style = parseStyle(css)
condense_rule(style) condense_rule(style)

View File

@ -8,7 +8,7 @@ from __future__ import with_statement
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2008, Marshall T. Vandegrift <llasram@gmail.com>' __copyright__ = '2008, Marshall T. Vandegrift <llasram@gmail.com>'
import os, re, logging, copy, unicodedata import os, re, logging, copy, unicodedata, numbers
from weakref import WeakKeyDictionary from weakref import WeakKeyDictionary
from xml.dom import SyntaxErr as CSSSyntaxError from xml.dom import SyntaxErr as CSSSyntaxError
from css_parser.css import (CSSStyleRule, CSSPageRule, CSSFontFaceRule, from css_parser.css import (CSSStyleRule, CSSPageRule, CSSFontFaceRule,
@ -527,7 +527,7 @@ class Style(object):
result = size result = size
else: else:
result = self._unit_convert(value, base=base, font=base) result = self._unit_convert(value, base=base, font=base)
if not isinstance(result, (int, float, long)): if not isinstance(result, numbers.Number):
return base return base
if result < 0: if result < 0:
result = normalize_fontsize("smaller", base) result = normalize_fontsize("smaller", base)
@ -562,20 +562,20 @@ class Style(object):
ans = self._unit_convert(str(img_size) + 'px', base=base) ans = self._unit_convert(str(img_size) + 'px', base=base)
else: else:
x = self._unit_convert(x, base=base) x = self._unit_convert(x, base=base)
if isinstance(x, (float, int, long)): if isinstance(x, numbers.Number):
ans = x ans = x
if ans is None: if ans is None:
x = self._element.get(attr) x = self._element.get(attr)
if x is not None: if x is not None:
x = self._unit_convert(x + 'px', base=base) x = self._unit_convert(x + 'px', base=base)
if isinstance(x, (float, int, long)): if isinstance(x, numbers.Number):
ans = x ans = x
if ans is None: if ans is None:
ans = self._unit_convert(str(img_size) + 'px', base=base) ans = self._unit_convert(str(img_size) + 'px', base=base)
maa = self._style.get('max-' + attr) maa = self._style.get('max-' + attr)
if maa is not None: if maa is not None:
x = self._unit_convert(maa, base=base) x = self._unit_convert(maa, base=base)
if isinstance(x, (int, float, long)) and (ans is None or x < ans): if isinstance(x, numbers.Number) and (ans is None or x < ans):
ans = x ans = x
return ans return ans

View File

@ -6,7 +6,7 @@ from __future__ import with_statement
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2008, Marshall T. Vandegrift <llasram@gmail.com>' __copyright__ = '2008, Marshall T. Vandegrift <llasram@gmail.com>'
import re, operator, math import re, operator, math, numbers
from collections import defaultdict from collections import defaultdict
from xml.dom import SyntaxErr from xml.dom import SyntaxErr
@ -28,7 +28,7 @@ STRIPNUM = re.compile(r'[-0-9]+$')
def asfloat(value, default): def asfloat(value, default):
if not isinstance(value, (int, long, float)): if not isinstance(value, numbers.Number):
value = default value = default
return float(value) return float(value)
@ -378,7 +378,7 @@ class CSSFlattener(object):
except: except:
font_size = self.sbase if self.sbase is not None else \ font_size = self.sbase if self.sbase is not None else \
self.context.source.fbase self.context.source.fbase
if tag == 'body' and isinstance(font_size, (int, float)): if tag == 'body' and isinstance(font_size, numbers.Number):
stylizer.body_font_size = font_size stylizer.body_font_size = font_size
if 'align' in node.attrib: if 'align' in node.attrib:
if tag != 'img': if tag != 'img':

View File

@ -7,6 +7,7 @@ __license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import numbers
from collections import Counter from collections import Counter
from calibre.ebooks.oeb.base import barename, XPath from calibre.ebooks.oeb.base import barename, XPath
@ -89,7 +90,7 @@ class RemoveFakeMargins(object):
pass pass
else: else:
if ((hasattr(ti, 'startswith') and ti.startswith('-')) or if ((hasattr(ti, 'startswith') and ti.startswith('-')) or
isinstance(ti, (int, float)) and ti < 0): isinstance(ti, numbers.Number) and ti < 0):
raise NegativeTextIndent() raise NegativeTextIndent()
return style.marginLeft, style.marginRight, style return style.marginLeft, style.marginRight, style
return '', '', None return '', '', None

View File

@ -10,6 +10,7 @@ __docformat__ = 'restructuredtext en'
import re import re
import struct import struct
import time import time
from polyglot.builtins import long_type
class PdbHeaderReader(object): class PdbHeaderReader(object):
@ -82,7 +83,6 @@ class PdbHeaderBuilder(object):
offset = 78 + (8 * nrecords) + 2 offset = 78 + (8 * nrecords) + 2
for id, record in enumerate(section_lengths): for id, record in enumerate(section_lengths):
out_stream.write(struct.pack('>LBBBB', long(offset), 0, 0, 0, 0)) out_stream.write(struct.pack('>LBBBB', long_type(offset), 0, 0, 0, 0))
offset += record offset += record
out_stream.write('\x00\x00') out_stream.write('\x00\x00')

View File

@ -6,7 +6,7 @@ __license__ = 'GPL v3'
__copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import sys, os import sys, os, numbers
from lxml import etree from lxml import etree
@ -222,7 +222,7 @@ class Box(list):
def to_html(self): def to_html(self):
ans = ['<%s>'%self.tag] ans = ['<%s>'%self.tag]
for elem in self: for elem in self:
if isinstance(elem, int): if isinstance(elem, numbers.Integral):
ans.append('<a name="page_%d"/>'%elem) ans.append('<a name="page_%d"/>'%elem)
else: else:
ans.append(elem.to_html()+' ') ans.append(elem.to_html()+' ')
@ -242,7 +242,7 @@ class ImageBox(Box):
if len(self) > 0: if len(self) > 0:
ans.append('<br/>') ans.append('<br/>')
for elem in self: for elem in self:
if isinstance(elem, int): if isinstance(elem, numbers.Integral):
ans.append('<a name="page_%d"/>'%elem) ans.append('<a name="page_%d"/>'%elem)
else: else:
ans.append(elem.to_html()+' ') ans.append(elem.to_html()+' ')

View File

@ -7,7 +7,7 @@ __license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import codecs, zlib import codecs, zlib, numbers
from io import BytesIO from io import BytesIO
from datetime import datetime from datetime import datetime
from binascii import hexlify from binascii import hexlify
@ -69,7 +69,7 @@ def serialize(o, stream):
elif isinstance(o, bool): elif isinstance(o, bool):
# Must check bool before int as bools are subclasses of int # Must check bool before int as bools are subclasses of int
stream.write_raw(b'true' if o else b'false') stream.write_raw(b'true' if o else b'false')
elif isinstance(o, (int, long)): elif isinstance(o, numbers.Integral):
stream.write_raw(str(o).encode('ascii') if ispy3 else bytes(o)) stream.write_raw(str(o).encode('ascii') if ispy3 else bytes(o))
elif hasattr(o, 'pdf_serialize'): elif hasattr(o, 'pdf_serialize'):
o.pdf_serialize(stream) o.pdf_serialize(stream)

View File

@ -7,7 +7,7 @@ __license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import json, os import json, os, numbers
from polyglot.builtins import map from polyglot.builtins import map
from math import floor from math import floor
from collections import defaultdict from collections import defaultdict
@ -418,7 +418,7 @@ class PDFWriter(QObject):
except Exception: except Exception:
doc_margins = None doc_margins = None
if doc_margins and isinstance(doc_margins, dict): if doc_margins and isinstance(doc_margins, dict):
doc_margins = {k:float(v) for k, v in doc_margins.iteritems() if isinstance(v, (float, int)) and k in {'right', 'top', 'left', 'bottom'}} doc_margins = {k:float(v) for k, v in doc_margins.iteritems() if isinstance(v, numbers.Number) and k in {'right', 'top', 'left', 'bottom'}}
if doc_margins: if doc_margins:
margin_top = margin_bottom = 0 margin_top = margin_bottom = 0
page_margins = self.convert_page_margins(doc_margins) page_margins = self.convert_page_margins(doc_margins)

View File

@ -7,7 +7,7 @@ __license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import hashlib import hashlib, numbers
from polyglot.builtins import map from polyglot.builtins import map
from PyQt5.Qt import QBuffer, QByteArray, QImage, Qt, QColor, qRgba, QPainter from PyQt5.Qt import QBuffer, QByteArray, QImage, Qt, QColor, qRgba, QPainter
@ -56,7 +56,7 @@ class IndirectObjects(object):
def __getitem__(self, o): def __getitem__(self, o):
try: try:
return self._map[id(self._list[o] if isinstance(o, int) else o)] return self._map[id(self._list[o] if isinstance(o, numbers.Integral) else o)]
except (KeyError, IndexError): except (KeyError, IndexError):
raise KeyError('The object %r was not found'%o) raise KeyError('The object %r was not found'%o)
@ -355,7 +355,7 @@ class PDFStream(object):
self.current_page.write_line() self.current_page.write_line()
for x in op: for x in op:
self.current_page.write( self.current_page.write(
(fmtnum(x) if isinstance(x, (int, long, float)) else x) + ' ') (fmtnum(x) if isinstance(x, numbers.Number) else x) + ' ')
def draw_path(self, path, stroke=True, fill=False, fill_rule='winding'): def draw_path(self, path, stroke=True, fill=False, fill_rule='winding'):
if not path.ops: if not path.ops:

View File

@ -15,7 +15,7 @@ from calibre.ebooks.metadata.opf2 import OPFCreator
from calibre.ebooks.conversion.preprocess import DocAnalysis from calibre.ebooks.conversion.preprocess import DocAnalysis
from calibre.utils.cleantext import clean_ascii_chars from calibre.utils.cleantext import clean_ascii_chars
from polyglot.builtins import unicode_type, map, range from polyglot.builtins import unicode_type, map, range, long_type
HTML_TEMPLATE = u'<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><title>%s </title></head><body>\n%s\n</body></html>' HTML_TEMPLATE = u'<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/><title>%s </title></head><body>\n%s\n</body></html>'
@ -64,7 +64,7 @@ def split_txt(txt, epub_split_size_kb=0):
txt = txt.encode('utf-8') txt = txt.encode('utf-8')
length_byte = len(txt) length_byte = len(txt)
# Calculating the average chunk value for easy splitting as EPUB (+2 as a safe margin) # Calculating the average chunk value for easy splitting as EPUB (+2 as a safe margin)
chunk_size = long(length_byte / (int(length_byte / (epub_split_size_kb * 1024)) + 2)) chunk_size = long_type(length_byte / (int(length_byte / (epub_split_size_kb * 1024)) + 2))
# if there are chunks with a superior size then go and break # if there are chunks with a superior size then go and break
parts = txt.split(b'\n\n') parts = txt.split(b'\n\n')
lengths = tuple(map(len, parts)) lengths = tuple(map(len, parts))

View File

@ -5,7 +5,7 @@ __license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import os import os, numbers
from functools import partial from functools import partial
from polyglot.builtins import map from polyglot.builtins import map
@ -121,7 +121,7 @@ class SaveToDiskAction(InterfaceAction):
Dispatcher(self.books_saved), paths, path) Dispatcher(self.books_saved), paths, path)
def save_library_format_by_ids(self, book_ids, fmt, single_dir=True): def save_library_format_by_ids(self, book_ids, fmt, single_dir=True):
if isinstance(book_ids, int): if isinstance(book_ids, numbers.Integral):
book_ids = [book_ids] book_ids = [book_ids]
rows = list(self.gui.library_view.ids_to_rows(book_ids).itervalues()) rows = list(self.gui.library_view.ids_to_rows(book_ids).itervalues())
rows = [self.gui.library_view.model().index(r, 0) for r in rows] rows = [self.gui.library_view.model().index(r, 0) for r in rows]

View File

@ -3,7 +3,7 @@
# License: GPLv3 Copyright: 2008, Kovid Goyal <kovid at kovidgoyal.net> # License: GPLv3 Copyright: 2008, Kovid Goyal <kovid at kovidgoyal.net>
from __future__ import print_function from __future__ import print_function
import re import re, numbers
from collections import defaultdict, namedtuple from collections import defaultdict, namedtuple
from io import BytesIO from io import BytesIO
from threading import Thread from threading import Thread
@ -773,7 +773,7 @@ class MetadataBulkDialog(QDialog, Ui_MetadataBulkDialog):
val = mi.format_field(field)[1] val = mi.format_field(field)[1]
else: else:
val = mi.get(field, None) val = mi.get(field, None)
if isinstance(val, (int, float, bool)): if isinstance(val, (numbers.Number, bool)):
val = str(val) val = str(val)
elif fm['is_csp']: elif fm['is_csp']:
# convert the csp dict into a list # convert the csp dict into a list

View File

@ -5,7 +5,7 @@ __license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import functools, re, os, traceback, errno, time import functools, re, os, traceback, errno, time, numbers
from collections import defaultdict, namedtuple from collections import defaultdict, namedtuple
from itertools import groupby from itertools import groupby
@ -580,7 +580,7 @@ class BooksModel(QAbstractTableModel): # {{{
return data return data
def get_book_info(self, index): def get_book_info(self, index):
if isinstance(index, int): if isinstance(index, numbers.Integral):
index = self.index(index, 0) index = self.index(index, 0)
# If index is not valid returns None # If index is not valid returns None
data = self.current_changed(index, None, False) data = self.current_changed(index, None, False)
@ -1649,7 +1649,7 @@ class DeviceBooksModel(BooksModel): # {{{
return (authors_to_string(au)) return (authors_to_string(au))
elif cname == 'size': elif cname == 'size':
size = self.db[self.map[row]].size size = self.db[self.map[row]].size
if not isinstance(size, (float, int)): if not isinstance(size, numbers.Number):
size = 0 size = 0
return (human_readable(size)) return (human_readable(size))
elif cname == 'timestamp': elif cname == 'timestamp':

View File

@ -1,7 +1,7 @@
from __future__ import print_function from __future__ import print_function
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
import sys, collections, operator, copy, re import sys, collections, operator, copy, re, numbers
from PyQt5.Qt import ( from PyQt5.Qt import (
Qt, QRectF, QFont, QColor, QPixmap, QGraphicsPixmapItem, QGraphicsItem, Qt, QRectF, QFont, QColor, QPixmap, QGraphicsPixmapItem, QGraphicsItem,
@ -451,7 +451,7 @@ class Line(QGraphicsItem):
if self.length_in_space > 0: if self.length_in_space > 0:
frac = 1 + float(delta)/self.length_in_space frac = 1 + float(delta)/self.length_in_space
for i in range(len(self.tokens)): for i in range(len(self.tokens)):
if isinstance(self.tokens[i], (int, float)): if isinstance(self.tokens[i], numbers.Number):
self.tokens[i] *= frac self.tokens[i] *= frac
self.current_width = self.line_length self.current_width = self.line_length
@ -495,7 +495,7 @@ class Line(QGraphicsItem):
painter.restore() painter.restore()
painter.save() painter.save()
for tok in self.tokens: for tok in self.tokens:
if isinstance(tok, (int, float)): if isinstance(tok, numbers.Number):
x += tok x += tok
elif isinstance(tok, Word): elif isinstance(tok, Word):
painter.setFont(tok.font) painter.setFont(tok.font)
@ -559,7 +559,7 @@ class Line(QGraphicsItem):
def __unicode__(self): def __unicode__(self):
s = u'' s = u''
for tok in self.tokens: for tok in self.tokens:
if isinstance(tok, (int, float)): if isinstance(tok, numbers.Number):
s += ' ' s += ' '
elif isinstance(tok, Word): elif isinstance(tok, Word):
s += unicode_type(tok.string) s += unicode_type(tok.string)

View File

@ -7,7 +7,7 @@ __license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import textwrap import textwrap, numbers
from PyQt5.Qt import (QWidget, QGridLayout, QGroupBox, QListView, Qt, QSpinBox, from PyQt5.Qt import (QWidget, QGridLayout, QGroupBox, QListView, Qt, QSpinBox,
QDoubleSpinBox, QCheckBox, QLineEdit, QComboBox, QLabel) QDoubleSpinBox, QCheckBox, QLineEdit, QComboBox, QLabel)
@ -90,7 +90,7 @@ class ConfigWidget(QWidget):
def create_widgets(self, opt): def create_widgets(self, opt):
val = self.plugin.prefs[opt.name] val = self.plugin.prefs[opt.name]
if opt.type == 'number': if opt.type == 'number':
c = QSpinBox if isinstance(opt.default, int) else QDoubleSpinBox c = QSpinBox if isinstance(opt.default, numbers.Integral) else QDoubleSpinBox
widget = c(self) widget = c(self)
widget.setValue(val) widget.setValue(val)
elif opt.type == 'string': elif opt.type == 'string':

View File

@ -7,6 +7,7 @@ __copyright__ = '2009, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import numbers
from PyQt5.Qt import QDialog, QVBoxLayout, QPlainTextEdit, QTimer, \ from PyQt5.Qt import QDialog, QVBoxLayout, QPlainTextEdit, QTimer, \
QDialogButtonBox, QPushButton, QApplication, QIcon, QMessageBox QDialogButtonBox, QPushButton, QApplication, QIcon, QMessageBox
@ -63,7 +64,7 @@ class UserDefinedDevice(QDialog):
res = '' res = ''
if len(new_devices) == 1: if len(new_devices) == 1:
def fmtid(x): def fmtid(x):
if isinstance(x, (int, long)): if isinstance(x, numbers.Integral):
x = hex(x) x = hex(x)
if not x.startswith('0x'): if not x.startswith('0x'):
x = '0x' + x x = '0x' + x

View File

@ -4,6 +4,7 @@
import errno import errno
import json import json
import numbers
import os import os
import sys import sys
import textwrap import textwrap
@ -267,9 +268,9 @@ class AdvancedTab(QWidget):
w = Choices w = Choices
elif isinstance(opt.default, bool): elif isinstance(opt.default, bool):
w = Bool w = Bool
elif isinstance(opt.default, (int, long)): elif isinstance(opt.default, numbers.Integral):
w = Int w = Int
elif isinstance(opt.default, float): elif isinstance(opt.default, numbers.Real):
w = Float w = Float
else: else:
w = Text w = Text

View File

@ -5,6 +5,7 @@
from __future__ import (unicode_literals, division, absolute_import, from __future__ import (unicode_literals, division, absolute_import,
print_function) print_function)
import numbers
from PyQt5.Qt import ( from PyQt5.Qt import (
Qt, QWidget, QSizePolicy, QSize, QRect, QConicalGradient, QPen, QBrush, Qt, QWidget, QSizePolicy, QSize, QRect, QConicalGradient, QPen, QBrush,
QPainter, QTimer, QVBoxLayout, QLabel, QStackedWidget, QDialog, QStackedLayout QPainter, QTimer, QVBoxLayout, QLabel, QStackedWidget, QDialog, QStackedLayout
@ -93,7 +94,7 @@ class ProgressSpinner(QWidget):
return self._size_hint return self._size_hint
def setSizeHint(self, val): def setSizeHint(self, val):
if isinstance(val, int): if isinstance(val, numbers.Integral):
val = QSize(val, val) val = QSize(val, val)
self._size_hint = val self._size_hint = val
self.update() self.update()

View File

@ -6,6 +6,7 @@ from __future__ import (unicode_literals, division, absolute_import,
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2014, Kovid Goyal <kovid at kovidgoyal.net>'
import numbers
from functools import partial from functools import partial
from PyQt5.Qt import QTextBlockUserData from PyQt5.Qt import QTextBlockUserData
@ -48,7 +49,7 @@ def create_lexer(base_class):
statestack.append(statestack[-1]) statestack.append(statestack[-1])
else: else:
statestack.append(state) statestack.append(state)
elif isinstance(new_state, int): elif isinstance(new_state, numbers.Integral):
# pop # pop
del statestack[new_state:] del statestack[new_state:]
elif new_state == '#push': elif new_state == '#push':

View File

@ -6,6 +6,7 @@ from __future__ import (unicode_literals, division, absolute_import,
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import numbers
from operator import attrgetter, methodcaller from operator import attrgetter, methodcaller
from collections import namedtuple from collections import namedtuple
from polyglot.builtins import map, unicode_type, range from polyglot.builtins import map, unicode_type, range
@ -50,8 +51,8 @@ class BasicSettings(QWidget): # {{{
getter = getter or methodcaller('isChecked') getter = getter or methodcaller('isChecked')
setter = setter or (lambda x, v: x.setChecked(v)) setter = setter or (lambda x, v: x.setChecked(v))
widget.toggled.connect(self.emit_changed) widget.toggled.connect(self.emit_changed)
elif isinstance(defval, (int, float)): elif isinstance(defval, numbers.Number):
widget = (QSpinBox if isinstance(defval, int) else QDoubleSpinBox)(self) widget = (QSpinBox if isinstance(defval, numbers.Integral) else QDoubleSpinBox)(self)
getter = getter or methodcaller('value') getter = getter or methodcaller('value')
setter = setter or (lambda x, v:x.setValue(v)) setter = setter or (lambda x, v:x.setValue(v))
widget.valueChanged.connect(self.emit_changed) widget.valueChanged.connect(self.emit_changed)

View File

@ -7,7 +7,7 @@ __license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2012, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import json, time import json, time, numbers
from PyQt5.Qt import QApplication, QEventLoop from PyQt5.Qt import QApplication, QEventLoop
@ -83,7 +83,7 @@ class PagePosition(object):
self._cpos = None self._cpos = None
def to_pos(self, pos): def to_pos(self, pos):
if isinstance(pos, (int, float)): if isinstance(pos, numbers.Number):
self.document.scroll_fraction = pos self.document.scroll_fraction = pos
else: else:
self.scroll_to_cfi(pos) self.scroll_to_cfi(pos)

View File

@ -5,7 +5,7 @@ __license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2012, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import re, codecs, os import re, codecs, os, numbers
from collections import namedtuple from collections import namedtuple
from types import StringType, UnicodeType from types import StringType, UnicodeType
@ -143,7 +143,7 @@ class BIBTEX(CatalogPlugin):
for field in fields: for field in fields:
if field.startswith('#'): if field.startswith('#'):
item = db.get_field(entry['id'],field,index_is_id=True) item = db.get_field(entry['id'],field,index_is_id=True)
if isinstance(item, (bool, float, int)): if isinstance(item, (bool, numbers.Number)):
item = repr(item) item = repr(item)
elif field == 'title_sort': elif field == 'title_sort':
item = entry['sort'] item = entry['sort']

View File

@ -6,7 +6,7 @@ __license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import json, re import json, re, numbers
from functools import partial from functools import partial
from calibre import prints, force_unicode from calibre import prints, force_unicode
@ -346,7 +346,7 @@ class CustomColumns(object):
series_id = self.conn.get('SELECT id from %s WHERE value=?'%table, series_id = self.conn.get('SELECT id from %s WHERE value=?'%table,
(series,), all=False) (series,), all=False)
if series_id is None: if series_id is None:
if isinstance(tweaks['series_index_auto_increment'], (int, float)): if isinstance(tweaks['series_index_auto_increment'], numbers.Number):
return float(tweaks['series_index_auto_increment']) return float(tweaks['series_index_auto_increment'])
return 1.0 return 1.0
series_indices = self.conn.get(''' series_indices = self.conn.get('''

View File

@ -7,7 +7,7 @@ __docformat__ = 'restructuredtext en'
The database used to store ebook metadata The database used to store ebook metadata
''' '''
import os, sys, shutil, cStringIO, glob, time, functools, traceback, re, \ import os, sys, shutil, cStringIO, glob, time, functools, traceback, re, \
json, uuid, hashlib, copy, types json, uuid, hashlib, copy, types, numbers
from collections import defaultdict, namedtuple from collections import defaultdict, namedtuple
import threading, random import threading, random
from itertools import repeat from itertools import repeat
@ -2224,7 +2224,7 @@ class LibraryDatabase2(LibraryDatabase, SchemaUpgrade, CustomColumns):
series_id = self.conn.get('SELECT id from series WHERE name=?', series_id = self.conn.get('SELECT id from series WHERE name=?',
(series,), all=False) (series,), all=False)
if series_id is None: if series_id is None:
if isinstance(tweaks['series_index_auto_increment'], (int, float)): if isinstance(tweaks['series_index_auto_increment'], numbers.Number):
return float(tweaks['series_index_auto_increment']) return float(tweaks['series_index_auto_increment'])
return 1.0 return 1.0
series_indices = self.conn.get( series_indices = self.conn.get(

View File

@ -6,7 +6,7 @@ from __future__ import (unicode_literals, division, absolute_import,
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>'
import errno, os import errno, os, numbers
from itertools import izip_longest from itertools import izip_longest
from collections import namedtuple, OrderedDict from collections import namedtuple, OrderedDict
from operator import attrgetter from operator import attrgetter
@ -248,7 +248,7 @@ def opts_to_parser(usage):
else: else:
name = '--' + opt.name.replace('_', '-') name = '--' + opt.name.replace('_', '-')
otype = 'string' otype = 'string'
if isinstance(opt.default, (int, long, float)): if isinstance(opt.default, numbers.Number):
otype = type(opt.default).__name__ otype = type(opt.default).__name__
add_option(name, type=otype) add_option(name, type=otype)
@ -278,7 +278,7 @@ def parse_config_file(path=DEFAULT_CONFIG):
val = rest val = rest
if isinstance(opt.default, bool): if isinstance(opt.default, bool):
val = val.lower() in ('true', 'yes', 'y') val = val.lower() in ('true', 'yes', 'y')
elif isinstance(opt.default, (int, long, float)): elif isinstance(opt.default, numbers.Number):
try: try:
val = type(opt.default)(rest) val = type(opt.default)(rest)
except Exception: except Exception:

View File

@ -141,7 +141,7 @@ class Route(object):
if '{' in default or '}' in default: if '{' in default or '}' in default:
raise route_error('The characters {} are not allowed in default values') raise route_error('The characters {} are not allowed in default values')
default = self.defaults[name] = eval(default) default = self.defaults[name] = eval(default)
if isinstance(default, (int, long, float)): if isinstance(default, numbers.Number):
self.type_checkers[name] = type(default) self.type_checkers[name] = type(default)
if is_sponge and not isinstance(default, type('')): if is_sponge and not isinstance(default, type('')):
raise route_error('Soak up path component must have a default value of string type') raise route_error('Soak up path component must have a default value of string type')

View File

@ -4,7 +4,7 @@
from __future__ import (unicode_literals, division, absolute_import, from __future__ import (unicode_literals, division, absolute_import,
print_function) print_function)
import socket, os, struct, errno import socket, os, struct, errno, numbers
from base64 import standard_b64encode from base64 import standard_b64encode
from collections import deque, namedtuple from collections import deque, namedtuple
from functools import partial from functools import partial
@ -16,7 +16,7 @@ from calibre.srv.web_socket import (
PING, PONG, PROTOCOL_ERROR, CONTINUATION, INCONSISTENT_DATA, CONTROL_CODES) PING, PONG, PROTOCOL_ERROR, CONTINUATION, INCONSISTENT_DATA, CONTROL_CODES)
from calibre.utils.monotonic import monotonic from calibre.utils.monotonic import monotonic
from calibre.utils.socket_inheritance import set_socket_inherit from calibre.utils.socket_inheritance import set_socket_inherit
from polyglot.builtins import range from polyglot.builtins import range, unicode_type
HANDSHAKE_STR = '''\ HANDSHAKE_STR = '''\
GET / HTTP/1.1\r GET / HTTP/1.1\r
@ -183,11 +183,11 @@ class WebSocketTest(BaseTest):
expected_messages, expected_controls = [], [] expected_messages, expected_controls = [], []
for ex in expected: for ex in expected:
if isinstance(ex, type('')): if isinstance(ex, unicode_type):
ex = TEXT, ex ex = TEXT, ex
elif isinstance(ex, bytes): elif isinstance(ex, bytes):
ex = BINARY, ex ex = BINARY, ex
elif isinstance(ex, int): elif isinstance(ex, numbers.Integral):
ex = ex, b'' ex = ex, b''
if ex[0] in CONTROL_CODES: if ex[0] in CONTROL_CODES:
expected_controls.append(ex) expected_controls.append(ex)

View File

@ -87,6 +87,7 @@ import socket
import threading import threading
import select import select
import traceback import traceback
import numbers
__all__ = ["Zeroconf", "ServiceInfo", "ServiceBrowser"] __all__ = ["Zeroconf", "ServiceInfo", "ServiceBrowser"]
@ -1138,7 +1139,7 @@ class ServiceInfo(object):
suffix = '' suffix = ''
elif isinstance(value, str): elif isinstance(value, str):
suffix = value suffix = value
elif isinstance(value, int): elif isinstance(value, numbers.Integral):
suffix = value and 'true' or 'false' suffix = value and 'true' or 'false'
else: else:
suffix = '' suffix = ''

View File

@ -31,6 +31,7 @@ import struct
import sys import sys
from calibre.constants import plugins from calibre.constants import plugins
from polyglot.builtins import long_type
chmlib, chmlib_err = plugins['chmlib'] chmlib, chmlib_err = plugins['chmlib']
if chmlib_err: if chmlib_err:
@ -401,7 +402,7 @@ class CHMFile:
if start == -1: if start == -1:
st = 0 st = 0
else: else:
st = long(start) st = long_type(start)
return chmlib.chm_retrieve_object(self.file, ui, st, len) return chmlib.chm_retrieve_object(self.file, ui, st, len)
else: else:
return (0, '') return (0, '')

View File

@ -6,7 +6,7 @@ __license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import os, re, cPickle, traceback import os, re, cPickle, traceback, numbers
from functools import partial from functools import partial
from collections import defaultdict from collections import defaultdict
from copy import deepcopy from copy import deepcopy
@ -37,7 +37,7 @@ class Option(object):
if self.type is None and action is None and choices is None: if self.type is None and action is None and choices is None:
if isinstance(default, float): if isinstance(default, float):
self.type = 'float' self.type = 'float'
elif isinstance(default, int) and not isinstance(default, bool): elif isinstance(default, numbers.Integral) and not isinstance(default, bool):
self.type = 'int' self.type = 'int'
self.choices = choices self.choices = choices
@ -234,7 +234,7 @@ class OptionSet(object):
def serialize_opt(self, val): def serialize_opt(self, val):
if val is val is True or val is False or val is None or \ if val is val is True or val is False or val is None or \
isinstance(val, (int, float, long, bytes, unicode_type)): isinstance(val, (numbers.Number, bytes, unicode_type)):
return repr(val) return repr(val)
pickle = cPickle.dumps(val, -1) pickle = cPickle.dumps(val, -1)
return 'cPickle.loads(%s)'%repr(pickle) return 'cPickle.loads(%s)'%repr(pickle)

View File

@ -8,7 +8,7 @@ __license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import re, string, traceback import re, string, traceback, numbers
from calibre import prints from calibre import prints
from calibre.constants import DEBUG from calibre.constants import DEBUG
@ -271,7 +271,7 @@ class TemplateFormatter(string.Formatter):
def format_field(self, val, fmt): def format_field(self, val, fmt):
# ensure we are dealing with a string. # ensure we are dealing with a string.
if isinstance(val, (int, float)): if isinstance(val, numbers.Number):
if val: if val:
val = unicode_type(val) val = unicode_type(val)
else: else:

View File

@ -12,7 +12,7 @@ __license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>' __copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en' __docformat__ = 'restructuredtext en'
import inspect, re, traceback import inspect, re, traceback, numbers
from math import trunc from math import trunc
from calibre import human_readable from calibre import human_readable
@ -136,7 +136,7 @@ class FormatterFunction(object):
return ret return ret
if isinstance(ret, list): if isinstance(ret, list):
return ','.join(ret) return ','.join(ret)
if isinstance(ret, (int, float, bool)): if isinstance(ret, (numbers.Number, bool)):
return unicode_type(ret) return unicode_type(ret)

View File

@ -6,7 +6,7 @@ __author__ = "Andrew Dalke <dalke@dalkescientific.com>"
_generator_name = __name__ + "-" + ".".join(map(str, __version__)) _generator_name = __name__ + "-" + ".".join(map(str, __version__))
import datetime import datetime, numbers
from polyglot.builtins import string_or_bytes from polyglot.builtins import string_or_bytes
# Could make this the base class; will need to add 'publish' # Could make this the base class; will need to add 'publish'
@ -166,12 +166,12 @@ class Image:
_element(handler, "link", self.link) _element(handler, "link", self.link)
width = self.width width = self.width
if isinstance(width, int): if isinstance(width, numbers.Integral):
width = IntElement("width", width) width = IntElement("width", width)
_opt_element(handler, "width", width) _opt_element(handler, "width", width)
height = self.height height = self.height
if isinstance(height, int): if isinstance(height, numbers.Integral):
height = IntElement("height", height) height = IntElement("height", height)
_opt_element(handler, "height", height) _opt_element(handler, "height", height)
@ -385,7 +385,7 @@ class RSS2(WriteXmlMixin):
self.cloud.publish(handler) self.cloud.publish(handler)
ttl = self.ttl ttl = self.ttl
if isinstance(self.ttl, int): if isinstance(self.ttl, numbers.Integral):
ttl = IntElement("ttl", ttl) ttl = IntElement("ttl", ttl)
_opt_element(handler, "tt", ttl) _opt_element(handler, "tt", ttl)

View File

@ -6,6 +6,7 @@ from __future__ import (unicode_literals, division, absolute_import,
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>'
import numbers
from ctypes import POINTER, WINFUNCTYPE, c_void_p, c_ulong, c_char_p, windll, byref from ctypes import POINTER, WINFUNCTYPE, c_void_p, c_ulong, c_char_p, windll, byref
from ctypes.wintypes import BOOL, DWORD, LPCWSTR, UINT from ctypes.wintypes import BOOL, DWORD, LPCWSTR, UINT
@ -87,10 +88,11 @@ def dde_error(instance):
def default_errcheck(result, func, args): def default_errcheck(result, func, args):
if (isinstance(result, (int, long)) and result == 0) or (getattr(result, 'value', False) is None): if (isinstance(result, numbers.Integral) and result == 0) or (getattr(result, 'value', False) is None):
dde_error(args[0]) dde_error(args[0])
return args return args
null = object() null = object()
@ -111,6 +113,7 @@ def cwrap(name, restype, *args, **kw):
func.errcheck=kw.get('errcheck', default_errcheck) func.errcheck=kw.get('errcheck', default_errcheck)
return func return func
GetLastError = cwrap('DdeGetLastError', UINT, a('instance', DWORD), errcheck=no_errcheck) GetLastError = cwrap('DdeGetLastError', UINT, a('instance', DWORD), errcheck=no_errcheck)
Initialize = cwrap('DdeInitializeW', UINT, a('instance_p', LPDWORD), a('callback', DDECALLBACK), a('command', DWORD), Initialize = cwrap('DdeInitializeW', UINT, a('instance_p', LPDWORD), a('callback', DDECALLBACK), a('command', DWORD),
@ -147,5 +150,6 @@ def send_dde_command(service, topic, command):
Disconnect(conversation) Disconnect(conversation)
Uninitialize(instance) Uninitialize(instance)
if __name__ == '__main__': if __name__ == '__main__':
send_dde_command('WinWord', 'System', '[REM_DDE_Direct][FileOpen("C:/cygwin64/home/kovid/demo.docx")]') send_dde_command('WinWord', 'System', '[REM_DDE_Direct][FileOpen("C:/cygwin64/home/kovid/demo.docx")]')

View File

@ -6,7 +6,7 @@ from __future__ import (unicode_literals, division, absolute_import,
__license__ = 'GPL v3' __license__ = 'GPL v3'
__copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>' __copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>'
import ctypes, ctypes.wintypes as types, _winreg as winreg, struct, datetime import ctypes, ctypes.wintypes as types, _winreg as winreg, struct, datetime, numbers
import winerror, win32con import winerror, win32con
# Binding to C library {{{ # Binding to C library {{{
@ -112,7 +112,7 @@ def convert_to_registry_data(value, has_expansions=False):
if isinstance(value, (list, tuple)): if isinstance(value, (list, tuple)):
buf = ctypes.create_unicode_buffer('\0'.join(map(type(''), value)) + '\0\0') buf = ctypes.create_unicode_buffer('\0'.join(map(type(''), value)) + '\0\0')
return buf, winreg.REG_MULTI_SZ, len(buf) * 2 return buf, winreg.REG_MULTI_SZ, len(buf) * 2
if isinstance(value, (int, long)): if isinstance(value, numbers.Integral):
try: try:
raw, dtype = struct.pack(str('L'), value), winreg.REG_DWORD raw, dtype = struct.pack(str('L'), value), winreg.REG_DWORD
except struct.error: except struct.error:

View File

@ -30,6 +30,7 @@ if is_py3:
codepoint_to_chr = chr codepoint_to_chr = chr
unicode_type = str unicode_type = str
string_or_bytes = str, bytes string_or_bytes = str, bytes
long_type = int
def iteritems(d): def iteritems(d):
return iter(d.items()) return iter(d.items())
@ -59,6 +60,7 @@ else:
codepoint_to_chr = unichr codepoint_to_chr = unichr
unicode_type = unicode unicode_type = unicode
string_or_bytes = unicode, bytes string_or_bytes = unicode, bytes
long_type = long
def iteritems(d): def iteritems(d):
return d.iteritems() return d.iteritems()