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.
'''
import re, os, shutil
import re, os, shutil, numbers
from calibre import CurrentDir
from calibre.customize import Plugin
@ -80,7 +80,7 @@ class OptionRecommendation(object):
self.option.choices:
raise ValueError('OpRec: %s: Recommended value not in choices'%
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(
self.recommended_value) + ' is not a string or a number')

View File

@ -9,6 +9,7 @@ __docformat__ = 'restructuredtext en'
SPOOL_SIZE = 30*1024*1024
import numbers
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 math import ceil, floor
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 1.0
if unwrap:
@ -38,7 +39,7 @@ def _get_next_series_num_for_list(series_indices, unwrap=True):
if i not in series_indices:
return i
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 1.0

View File

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

View File

@ -6,7 +6,7 @@ from __future__ import (unicode_literals, division, absolute_import,
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import inspect, time
import inspect, time, numbers
from io import BytesIO
from repr import repr
from functools import partial
@ -109,7 +109,7 @@ class LegacyTest(BaseTest):
def get_values(db):
ans = {}
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 = type('')(label)
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>'
__docformat__ = 'restructuredtext en'
import weakref, operator
import weakref, operator, numbers
from functools import partial
from itertools import izip, imap
from polyglot.builtins import map, unicode_type, range
@ -98,7 +98,7 @@ class View(object):
'marked': self.get_marked,
'series_sort':self.get_series_sort,
}.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.field_metadata.custom_field_prefix + label)
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.ebooks.metadata import authors_to_sort_string, authors_to_string
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'
THUMBPATH = 'Sony_Reader/database/cache/books/%s/thumbnail/main_thumbnail.jpg'
@ -330,7 +330,7 @@ class PRST1(USBMS):
cursor.execute(query)
row = cursor.fetchone()
return long(row[0])
return long_type(row[0])
def get_database_min_id(self, source_id):
sequence_min = 0

View File

@ -7,7 +7,7 @@ Code for the conversion of ebook formats and the reading of metadata
from various formats.
'''
import traceback, os, re
import traceback, os, re, numbers
from calibre import CurrentDir, prints
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):
' Return value in pts'
if isinstance(value, (int, long, float)):
if isinstance(value, numbers.Number):
return value
try:
return float(value) * 72.0 / dpi

View File

@ -7,7 +7,7 @@ __docformat__ = 'restructuredtext en'
Command line interface to conversion sub-system
'''
import sys, os
import sys, os, numbers
from optparse import OptionGroup, Option
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 \
'store_true'
else:
if isinstance(rec.recommended_value, int):
if isinstance(rec.recommended_value, numbers.Integral):
attrs['type'] = 'int'
if isinstance(rec.recommended_value, float):
if isinstance(rec.recommended_value, numbers.Real):
attrs['type'] = 'float'
if opt.long_switch == 'verbose':

View File

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

View File

@ -6,7 +6,7 @@ from __future__ import (unicode_literals, division, absolute_import,
print_function)
from functools import partial
from collections import OrderedDict
import operator
import operator, numbers
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):
if isinstance(raw, (int, long, float)):
if isinstance(raw, numbers.Number):
return raw, default_unit
try:
return float(raw), default_unit

View File

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

View File

@ -6,6 +6,7 @@ from __future__ import (unicode_literals, division, absolute_import,
__license__ = 'GPL v3'
__copyright__ = '2015, Kovid Goyal <kovid at kovidgoyal.net>'
import numbers
from collections import Counter, defaultdict
from operator import attrgetter
@ -232,7 +233,7 @@ class TextStyle(DOCXStyle):
except (ValueError, TypeError, AttributeError):
self.spacing = None
va = css.first_vertical_align
if isinstance(va, (int, float)):
if isinstance(va, numbers.Number):
self.vertical_align = str(int(va * 2))
else:
val = {
@ -254,7 +255,7 @@ class TextStyle(DOCXStyle):
elif self.padding != padding:
self.padding = ignore
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 = min(96, max(2, int(val * 8)))
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, 'css_margin_' + edge, css._style.get('margin-' + 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 = min(96, max(2, int(val * 8)))
setattr(self, 'border_%s_width' % edge, val)

View File

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

View File

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

View File

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

View File

@ -1,7 +1,7 @@
from __future__ import print_function
__license__ = 'GPL v3'
__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.pylrs.pylrs import TextBlock, Text, CR, Span, \
@ -137,7 +137,7 @@ class Cell(object):
mwidth = 0
for token, attrs in tokens(tb):
font = default_font
if isinstance(token, int): # Handle para and line breaks
if isinstance(token, numbers.Integral): # Handle para and line breaks
continue
if isinstance(token, Plot):
return self.pts_to_pixels(token.xsize)
@ -178,7 +178,7 @@ class Cell(object):
ls = self.pts_to_pixels(attrs.get('baselineskip', ts['baselineskip']))+\
self.pts_to_pixels(attrs.get('linespace', ts['linespace']))
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
top = bottom
else:

View File

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

View File

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

View File

@ -7,7 +7,7 @@ __license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import struct, datetime, os
import struct, datetime, os, numbers
from calibre.utils.date import utc_tz
from calibre.ebooks.mobi.reader.headers import NULL_INDEX
@ -598,7 +598,7 @@ class TextRecord(object): # {{{
self.trailing_data['raw_bytes'] = raw_trailing_bytes
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'%
(idx, typ, val))

View File

@ -9,6 +9,7 @@ __copyright__ = '2008, Marshall T. Vandegrift <llasram@gmail.cam>'
import copy
import re
import numbers
from lxml import etree
from calibre.ebooks.oeb.base import namespace, barename
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):
if not isinstance(value, (int, long, float)):
if not isinstance(value, numbers.Number):
return 0.0
return float(value)
@ -531,9 +532,9 @@ class MobiMLizer(object):
valign = style['vertical-align']
not_baseline = valign in ('super', 'sub', 'text-top',
'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 (
isinstance(valign, (float, int)) and valign > 0)
isinstance(valign, numbers.Number) and valign > 0)
vtag = 'sup' if issup else 'sub'
if not_baseline and not ignore_valign and tag not in NOT_VTAGS and not isblock:
nroot = etree.Element(XHTML('html'), nsmap=MOBI_NSMAP)

View File

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

View File

@ -7,7 +7,7 @@ __license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import random
import random, numbers
from io import BytesIO
from collections import OrderedDict
from struct import pack
@ -67,7 +67,7 @@ class Header(OrderedDict):
positions[name] = buf.tell()
if val is None:
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'
val = pack(b'>'+fmt, val)
buf.write(val)
@ -83,6 +83,3 @@ class Header(OrderedDict):
def format_value(self, name, val):
return val

View File

@ -7,7 +7,7 @@ __license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import os
import os, numbers
from io import BytesIO
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'])
else:
pos = bm['pos']
if isinstance(pos, (int, float)):
if isinstance(pos, numbers.Number):
pos = unicode_type(pos)
else:
pos = pos.replace(u'^', BM_LEGACY_ESC)

View File

@ -6,6 +6,7 @@ from __future__ import (unicode_literals, division, absolute_import,
__license__ = 'GPL v3'
__copyright__ = '2013, Kovid Goyal <kovid at kovidgoyal.net>'
import numbers
from polyglot.builtins import zip, string_or_bytes
from functools import wraps
@ -392,7 +393,7 @@ def test_normalization(return_tests=False): # {{{
tuple('0 0 0 0'.split()) : '0',
}.iteritems():
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()))
style = parseStyle(css)
condense_rule(style)

View File

@ -8,7 +8,7 @@ from __future__ import with_statement
__license__ = 'GPL v3'
__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 xml.dom import SyntaxErr as CSSSyntaxError
from css_parser.css import (CSSStyleRule, CSSPageRule, CSSFontFaceRule,
@ -527,7 +527,7 @@ class Style(object):
result = size
else:
result = self._unit_convert(value, base=base, font=base)
if not isinstance(result, (int, float, long)):
if not isinstance(result, numbers.Number):
return base
if result < 0:
result = normalize_fontsize("smaller", base)
@ -562,20 +562,20 @@ class Style(object):
ans = self._unit_convert(str(img_size) + 'px', base=base)
else:
x = self._unit_convert(x, base=base)
if isinstance(x, (float, int, long)):
if isinstance(x, numbers.Number):
ans = x
if ans is None:
x = self._element.get(attr)
if x is not None:
x = self._unit_convert(x + 'px', base=base)
if isinstance(x, (float, int, long)):
if isinstance(x, numbers.Number):
ans = x
if ans is None:
ans = self._unit_convert(str(img_size) + 'px', base=base)
maa = self._style.get('max-' + attr)
if maa is not None:
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
return ans

View File

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

View File

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

View File

@ -10,6 +10,7 @@ __docformat__ = 'restructuredtext en'
import re
import struct
import time
from polyglot.builtins import long_type
class PdbHeaderReader(object):
@ -82,7 +83,6 @@ class PdbHeaderBuilder(object):
offset = 78 + (8 * nrecords) + 2
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
out_stream.write('\x00\x00')

View File

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

View File

@ -7,7 +7,7 @@ __license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import codecs, zlib
import codecs, zlib, numbers
from io import BytesIO
from datetime import datetime
from binascii import hexlify
@ -69,7 +69,7 @@ def serialize(o, stream):
elif isinstance(o, bool):
# Must check bool before int as bools are subclasses of int
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))
elif hasattr(o, 'pdf_serialize'):
o.pdf_serialize(stream)

View File

@ -7,7 +7,7 @@ __license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid at kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import json, os
import json, os, numbers
from polyglot.builtins import map
from math import floor
from collections import defaultdict
@ -418,7 +418,7 @@ class PDFWriter(QObject):
except Exception:
doc_margins = None
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:
margin_top = margin_bottom = 0
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>'
__docformat__ = 'restructuredtext en'
import hashlib
import hashlib, numbers
from polyglot.builtins import map
from PyQt5.Qt import QBuffer, QByteArray, QImage, Qt, QColor, qRgba, QPainter
@ -56,7 +56,7 @@ class IndirectObjects(object):
def __getitem__(self, o):
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):
raise KeyError('The object %r was not found'%o)
@ -355,7 +355,7 @@ class PDFStream(object):
self.current_page.write_line()
for x in op:
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'):
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.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>'
@ -64,7 +64,7 @@ def split_txt(txt, epub_split_size_kb=0):
txt = txt.encode('utf-8')
length_byte = len(txt)
# 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
parts = txt.split(b'\n\n')
lengths = tuple(map(len, parts))

View File

@ -5,7 +5,7 @@ __license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import os
import os, numbers
from functools import partial
from polyglot.builtins import map
@ -121,7 +121,7 @@ class SaveToDiskAction(InterfaceAction):
Dispatcher(self.books_saved), paths, path)
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]
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]

View File

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

View File

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

View File

@ -1,7 +1,7 @@
from __future__ import print_function
__license__ = 'GPL v3'
__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 (
Qt, QRectF, QFont, QColor, QPixmap, QGraphicsPixmapItem, QGraphicsItem,
@ -451,7 +451,7 @@ class Line(QGraphicsItem):
if self.length_in_space > 0:
frac = 1 + float(delta)/self.length_in_space
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.current_width = self.line_length
@ -495,7 +495,7 @@ class Line(QGraphicsItem):
painter.restore()
painter.save()
for tok in self.tokens:
if isinstance(tok, (int, float)):
if isinstance(tok, numbers.Number):
x += tok
elif isinstance(tok, Word):
painter.setFont(tok.font)
@ -559,7 +559,7 @@ class Line(QGraphicsItem):
def __unicode__(self):
s = u''
for tok in self.tokens:
if isinstance(tok, (int, float)):
if isinstance(tok, numbers.Number):
s += ' '
elif isinstance(tok, Word):
s += unicode_type(tok.string)

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -5,7 +5,7 @@ __license__ = 'GPL v3'
__copyright__ = '2012, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import re, codecs, os
import re, codecs, os, numbers
from collections import namedtuple
from types import StringType, UnicodeType
@ -143,7 +143,7 @@ class BIBTEX(CatalogPlugin):
for field in fields:
if field.startswith('#'):
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)
elif field == 'title_sort':
item = entry['sort']

View File

@ -6,7 +6,7 @@ __license__ = 'GPL v3'
__copyright__ = '2010, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import json, re
import json, re, numbers
from functools import partial
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,), all=False)
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 1.0
series_indices = self.conn.get('''

View File

@ -7,7 +7,7 @@ __docformat__ = 'restructuredtext en'
The database used to store ebook metadata
'''
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
import threading, random
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,), all=False)
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 1.0
series_indices = self.conn.get(

View File

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

View File

@ -141,7 +141,7 @@ class Route(object):
if '{' in default or '}' in default:
raise route_error('The characters {} are not allowed in default values')
default = self.defaults[name] = eval(default)
if isinstance(default, (int, long, float)):
if isinstance(default, numbers.Number):
self.type_checkers[name] = type(default)
if is_sponge and not isinstance(default, 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,
print_function)
import socket, os, struct, errno
import socket, os, struct, errno, numbers
from base64 import standard_b64encode
from collections import deque, namedtuple
from functools import partial
@ -16,7 +16,7 @@ from calibre.srv.web_socket import (
PING, PONG, PROTOCOL_ERROR, CONTINUATION, INCONSISTENT_DATA, CONTROL_CODES)
from calibre.utils.monotonic import monotonic
from calibre.utils.socket_inheritance import set_socket_inherit
from polyglot.builtins import range
from polyglot.builtins import range, unicode_type
HANDSHAKE_STR = '''\
GET / HTTP/1.1\r
@ -183,11 +183,11 @@ class WebSocketTest(BaseTest):
expected_messages, expected_controls = [], []
for ex in expected:
if isinstance(ex, type('')):
if isinstance(ex, unicode_type):
ex = TEXT, ex
elif isinstance(ex, bytes):
ex = BINARY, ex
elif isinstance(ex, int):
elif isinstance(ex, numbers.Integral):
ex = ex, b''
if ex[0] in CONTROL_CODES:
expected_controls.append(ex)

View File

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

View File

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

View File

@ -6,7 +6,7 @@ __license__ = 'GPL v3'
__copyright__ = '2011, Kovid Goyal <kovid@kovidgoyal.net>'
__docformat__ = 'restructuredtext en'
import os, re, cPickle, traceback
import os, re, cPickle, traceback, numbers
from functools import partial
from collections import defaultdict
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 isinstance(default, 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.choices = choices
@ -234,7 +234,7 @@ class OptionSet(object):
def serialize_opt(self, val):
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)
pickle = cPickle.dumps(val, -1)
return 'cPickle.loads(%s)'%repr(pickle)

View File

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

View File

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

View File

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

View File

@ -6,6 +6,7 @@ from __future__ import (unicode_literals, division, absolute_import,
__license__ = 'GPL v3'
__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.wintypes import BOOL, DWORD, LPCWSTR, UINT
@ -87,10 +88,11 @@ def dde_error(instance):
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])
return args
null = object()
@ -111,6 +113,7 @@ def cwrap(name, restype, *args, **kw):
func.errcheck=kw.get('errcheck', default_errcheck)
return func
GetLastError = cwrap('DdeGetLastError', UINT, a('instance', DWORD), errcheck=no_errcheck)
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)
Uninitialize(instance)
if __name__ == '__main__':
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'
__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
# Binding to C library {{{
@ -112,7 +112,7 @@ def convert_to_registry_data(value, has_expansions=False):
if isinstance(value, (list, tuple)):
buf = ctypes.create_unicode_buffer('\0'.join(map(type(''), value)) + '\0\0')
return buf, winreg.REG_MULTI_SZ, len(buf) * 2
if isinstance(value, (int, long)):
if isinstance(value, numbers.Integral):
try:
raw, dtype = struct.pack(str('L'), value), winreg.REG_DWORD
except struct.error:

View File

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