reportlab: attempt to remove type() checking in favour of isinstance
authorrgbecker
Thu, 25 Jun 2009 14:35:38 +0000
changeset 3180 349e9644fce8
parent 3179 4c4576402c25
child 3182 511218046ef9
reportlab: attempt to remove type() checking in favour of isinstance
src/reportlab/graphics/renderPM.py
src/reportlab/lib/normalDate.py
src/reportlab/lib/utils.py
src/reportlab/pdfgen/canvas.py
src/reportlab/platypus/tables.py
--- a/src/reportlab/graphics/renderPM.py	Thu Jun 25 14:35:02 2009 +0000
+++ b/src/reportlab/graphics/renderPM.py	Thu Jun 25 14:35:38 2009 +0000
@@ -31,9 +31,6 @@
         (str(errMsg)!='No module named _renderPM' and "it may be the wrong version or badly installed!" or
                                     "see http://www.reportlab.org/rl_addons.html")
 
-from types import TupleType, ListType
-_SeqTypes = (TupleType,ListType)
-
 def _getImage():
     try:
         from PIL import Image
--- a/src/reportlab/lib/normalDate.py	Thu Jun 25 14:35:02 2009 +0000
+++ b/src/reportlab/lib/normalDate.py	Thu Jun 25 14:35:38 2009 +0000
@@ -23,12 +23,11 @@
 _monthName = ['January', 'February', 'March', 'April', 'May', 'June',
               'July','August','September','October','November','December']
 
-from types import IntType, StringType, ListType, TupleType
 import string, re, time, datetime
 if hasattr(time,'struct_time'):
-    _DateSeqTypes = (ListType,TupleType,time.struct_time)
+    _DateSeqTypes = (list,tuple,time.struct_time)
 else:
-    _DateSeqTypes = (ListType,TupleType)
+    _DateSeqTypes = (list,tuple)
 
 _fmtPat = re.compile('\\{(m{1,5}|yyyy|yy|d{1,4})\\}',re.MULTILINE|re.IGNORECASE)
 _iso_re = re.compile(r'(\d\d\d\d|\d\d)-(\d\d)-(\d\d)')
@@ -131,14 +130,14 @@
 
     def add(self, days):
         """add days to date; use negative integers to subtract"""
-        if not type(days) is IntType:
+        if not isinstance(days,int):
             raise NormalDateException( \
                 'add method parameter must be integer type')
         self.normalize(self.scalar() + days)
 
     def __add__(self, days):
         """add integer to normalDate and return a new, calculated value"""
-        if not type(days) is IntType:
+        if not isinstance(days,int):
             raise NormalDateException( \
                 '__add__ parameter must be integer type')
         cloned = self.clone()
@@ -193,13 +192,13 @@
         return value may be negative, since calculation is
         self.scalar() - arg
         """
-        if type(normalDate) is _NDType:
+        if isinstance(normalDate,NormalDate):
             return self.scalar() - normalDate.scalar()
         else:
             return self.scalar() - NormalDate(normalDate).scalar()
 
     def equals(self, target):
-        if type(target) is _NDType:
+        if isinstance(target,NormalDate):
             if target is None:
                 return self.normalDate is None
             else:
@@ -303,7 +302,7 @@
 
     def _isValidNormalDate(self, normalDate):
         """checks for date validity in [-]yyyymmdd format"""
-        if type(normalDate) is not IntType:
+        if not isinstance(normalDate,int):
             return 0
         if len(repr(normalDate)) > 9:
             return 0
@@ -406,7 +405,7 @@
     def range(self, days):
         """Return a range of normalDates as a list.  Parameter
         may be an int or normalDate."""
-        if type(days) is not IntType:
+        if not isinstance(days,int):
             days = days - self  # if not int, assume arg is normalDate type
         r = []
         for i in range(days):
@@ -458,10 +457,9 @@
         """
         accepts date as scalar string/integer (yyyymmdd) or tuple
         (year, month, day, ...)"""
-        tn=type(normalDate)
-        if tn is IntType:
+        if isinstance(normalDate,int):
             self.normalDate = normalDate
-        elif tn is StringType:
+        elif isinstance(normalDate,basestring):
             try:
                 self.normalDate = int(normalDate)
             except:
@@ -470,9 +468,9 @@
                     self.setNormalDate(m.group(1)+m.group(2)+m.group(3))
                 else:
                     raise NormalDateException("unable to setNormalDate(%s)" % `normalDate`)
-        elif tn in _DateSeqTypes:
+        elif isinstance(normalDate,_DateSeqTypes):
             self.normalDate = int("%04d%02d%02d" % normalDate[:3])
-        elif tn is _NDType:
+        elif isinstance(normalDate,NormalDate):
             self.normalDate = normalDate.normalDate
         elif isinstance(normalDate,(datetime.datetime,datetime.date)):
             self.normalDate = (normalDate.year*100+normalDate.month)*100+normalDate.day
@@ -492,12 +490,12 @@
     __setstate__ = setNormalDate
 
     def __sub__(self, v):
-        if type(v) is IntType:
+        if isinstance(v,int):
             return self.__add__(-v)
         return self.scalar() - v.scalar()
 
     def __rsub__(self,v):
-        if type(v) is IntType:
+        if isinstance(v,int):
             return NormalDate(v) - self
         else:
             return v.scalar() - self.scalar()
@@ -529,7 +527,7 @@
 
 def firstDayOfYear(year):
     """number of days to the first of the year, relative to Jan 1, 1900"""
-    if type(year) is not IntType:
+    if not isinstance(year,int):
         msg = "firstDayOfYear() expected integer, got %s" % type(year)
         raise NormalDateException(msg)
     if year == 0:
@@ -548,11 +546,10 @@
 
 def FND(d):
     '''convert to ND if required'''
-    return (type(d) is _NDType) and d or ND(d)
+    return isinstance(d,NormalDate) and d or ND(d)
 
 Epoch=bigBang()
 ND=NormalDate
-_NDType = type(Epoch)
 BDEpoch=ND(15821018)
 BDEpochScalar = -115857
 
@@ -562,20 +559,20 @@
     """
     def add(self, days):
         """add days to date; use negative integers to subtract"""
-        if not type(days) is IntType:
-            raise NormalDateException('add method parameter must be integer type')
+        if not isinstance(days,int):
+            raise NormalDateException('add method parameter must be integer')
         self.normalize(self.scalar() + days)
 
     def __add__(self, days):
         """add integer to BusinessDate and return a new, calculated value"""
-        if not type(days) is IntType:
-            raise NormalDateException('__add__ parameter must be integer type')
+        if not isinstance(days,int):
+            raise NormalDateException('__add__ parameter must be integer')
         cloned = self.clone()
         cloned.add(days)
         return cloned
 
     def __sub__(self, v):
-        return type(v) is IntType and self.__add__(-v) or self.scalar() - v.scalar()
+        return isinstance(v,int) and self.__add__(-v) or self.scalar() - v.scalar()
 
     def asNormalDate(self):
         return ND(self.normalDate)
--- a/src/reportlab/lib/utils.py	Thu Jun 25 14:35:02 2009 +0000
+++ b/src/reportlab/lib/utils.py	Thu Jun 25 14:35:38 2009 +0000
@@ -10,15 +10,10 @@
 except:
     from md5 import md5
 from reportlab.lib.logger import warnOnce
-from types import *
 from rltempfile import get_rl_tempfile, get_rl_tempdir, _rl_getuid
-SeqTypes = (ListType,TupleType)
-if sys.hexversion<0x2020000:
-    def isSeqType(v):
-        return type(v) in SeqTypes
-else:
-    def isSeqType(v):
-        return isinstance(v,(tuple,list))
+
+def isSeqType(v,_st=(tuple,list)):
+    return isinstance(v,_st)
 
 if sys.hexversion<0x2030000:
     True = 1
@@ -372,19 +367,19 @@
         if func:
             v = func(av)
         else:
-            t = type(v)
-            if t is StringType:
+            if isinstance(v,basestring):
+                if isinstance(v,unicode): v = v.encode('utf8')
                 v = av
-            elif t is FloatType:
+            elif isinstance(v,float):
                 v = float(av)
-            elif t is IntType:
+            elif isinstance(v,int):
                 v = int(av)
-            elif t is ListType:
+            elif isinstance(v,list):
                 v = list(eval(av))
-            elif t is TupleType:
+            elif isinstance(v,tuple):
                 v = tuple(eval(av))
             else:
-                raise TypeError, "Can't convert string '%s' to %s" % (av,str(t))
+                raise TypeError("Can't convert string %r to %s" % (av,type(v)))
         return v
 
     A = sys.argv[1:]
--- a/src/reportlab/pdfgen/canvas.py	Thu Jun 25 14:35:02 2009 +0000
+++ b/src/reportlab/pdfgen/canvas.py	Thu Jun 25 14:35:38 2009 +0000
@@ -14,7 +14,6 @@
 import re
 from string import join, split, strip, atoi, replace, upper, digits
 import tempfile
-from types import *
 from math import sin, cos, tan, pi, ceil
 try:
     from hashlib import md5
@@ -31,9 +30,7 @@
 from reportlab.lib.boxstuff import aspectRatioFix
 
 digitPat = re.compile('\d')  #used in decimal alignment
-
 zlib = import_zlib()
-_SeqTypes=(TupleType,ListType)
 
 # Robert Kern
 # Constants for closing paths.
@@ -380,7 +377,7 @@
     def setKeywords(self, keywords):
         """write a list of keywords into the PDF file which shows in document properties.
         Either submit a single string or a list/tuple"""
-        if type(keywords) in (TupleType, ListType):
+        if isinstance(keywords,(list,tuple)):
             keywords = ', '.join(keywords)
         self._doc.setKeywords(keywords)
 
@@ -1474,9 +1471,9 @@
 
     def setDash(self, array=[], phase=0):
         """Two notations.  pass two numbers, or an array and phase"""
-        if type(array) == IntType or type(array) == FloatType:
+        if isinstance(array,(int,float)):
             self._code.append('[%s %s] 0 d' % (array, phase))
-        elif type(array) == ListType or type(array) == TupleType:
+        elif isinstance(array,(tuple,list)):
             assert phase >= 0, "phase is a length in user space"
             textarray = ' '.join(map(str, array))
             self._code.append('[%s] %s d' % (textarray, phase))
--- a/src/reportlab/platypus/tables.py	Thu Jun 25 14:35:02 2009 +0000
+++ b/src/reportlab/platypus/tables.py	Thu Jun 25 14:35:38 2009 +0000
@@ -24,7 +24,6 @@
 from reportlab.lib.utils import fp_str
 from reportlab.pdfbase.pdfmetrics import stringWidth
 import operator, string
-from types import TupleType, ListType, StringType, FloatType, IntType
 
 class CellStyle(PropertySet):
     defaults = {
@@ -102,11 +101,8 @@
     def getCommands(self):
         return self._cmds
 
-TableStyleType = type(TableStyle())
-_SeqTypes = (TupleType, ListType)
-
 def _rowLen(x):
-    return type(x) not in _SeqTypes and 1 or len(x)
+    return not isinstance(x,(tuple,list)) and 1 or len(x)
 
 def _calc_pc(V,avail):
     '''check list V for percentage or * values
@@ -124,7 +120,7 @@
     s = avail
     w = n = 0.
     for v in V:
-        if type(v) is type(""):
+        if isinstance(v,basestring):
             v = v.strip()
             if not v:
                 v = None
@@ -225,12 +221,12 @@
         self.ident = ident
         self.hAlign = hAlign or 'CENTER'
         self.vAlign = vAlign or 'MIDDLE'
-        if type(data) not in _SeqTypes:
+        if not isinstance(data,(tuple,list)):
             raise ValueError("%s invalid data type" % self.identity())
         self._nrows = nrows = len(data)
         self._cellvalues = []
-        _seqCW = type(colWidths) in _SeqTypes
-        _seqRH = type(rowHeights) in _SeqTypes
+        _seqCW = isinstance(colWidths,(tuple,list))
+        _seqRH = isinstance(rowHeights,(tuple,list))
         if nrows: self._ncols = ncols = max(map(_rowLen,data))
         elif colWidths and _seqCW: ncols = len(colWidths)
         else: ncols = 0
@@ -315,7 +311,7 @@
         def normCell(stuff):
             if stuff is None:
                 return ''
-            elif type(stuff) == type(u''):
+            elif isinstance(stuff,unicode):
                 return stuff.encode('utf8')
             else:
                 return stuff
@@ -339,9 +335,8 @@
             for i in xrange(nr):
                 for j in xrange(nc):
                     v = cv[i][j]
-                    t = type(v)
-                    if t in _SeqTypes or isinstance(v,Flowable):
-                        if not t in _SeqTypes: v = (v,)
+                    if isinstance(v,(list,tuple,Flowable)):
+                        if not isinstance(v,(tuple,list)): v = (v,)
                         r = ''
                         for vij in v:
                             r = vij.identity(maxLen)
@@ -352,7 +347,7 @@
                     else:
                         v = v is None and '' or str(v)
                         ix, jx, vx = i, j, v
-                        b = (vx and t is StringType) and 1 or 0
+                        b = (vx and isinstance(v,basestring)) and 1 or 0
                         if maxLen: vx = vx[:maxLen]
                     if b: break
                 if b: break
@@ -461,15 +456,15 @@
                 w = max(w,ew)
             return w
         elif isinstance(v,Flowable) and v._fixedWidth:
-            if hasattr(v, 'width') and type(v.width) in (IntType,FloatType): return v.width
-            if hasattr(v, 'drawWidth') and type(v.drawWidth) in (IntType,FloatType): return v.drawWidth
+            if hasattr(v, 'width') and isinstance(v.width,(int,float)): return v.width
+            if hasattr(v, 'drawWidth') and isinstance(v.drawWidth,(int,float)): return v.drawWidth
         # Even if something is fixedWidth, the attribute to check is not
         # necessarily consistent (cf. Image.drawWidth).  Therefore, we'll
         # be extra-careful and fall through to this code if necessary.
         if hasattr(v, 'minWidth'):
             try:
                 w = v.minWidth() # should be all flowables
-                if type(w) in (FloatType,IntType): return w
+                if isinstance(w,(float,int)): return w
             except AttributeError:
                 pass
         v = (v is not None and str(v) or '').split("\n")
@@ -608,7 +603,7 @@
 
     def _canGetWidth(self, thing):
         "Can we work out the width quickly?"
-        if isinstance(thing,(ListType, TupleType)):
+        if isinstance(thing,(list, tuple)):
             for elem in thing:
                 if not self._canGetWidth(elem):
                     return 0
@@ -644,7 +639,7 @@
                 percentDefined += 1
                 percentTotal += float(w[:-1])
             else:
-                assert type(w) in (IntType, FloatType)
+                assert isinstance(w,(int,float))
                 totalDefined = totalDefined + w
         if verbose: print 'prelim width calculation.  %d columns, %d undefined width, %0.2f units remain' % (
             self._ncols, numberUndefined, availWidth - totalDefined)
@@ -926,7 +921,7 @@
                 value.sort()
 
     def setStyle(self, tblstyle):
-        if type(tblstyle) is not TableStyleType:
+        if not isinstance(tblstyle,TableStyle):
             tblstyle = TableStyle(tblstyle)
         for cmd in tblstyle.getCommands():
             self._addCommand(cmd)
@@ -998,7 +993,7 @@
         ccap, cdash, cjoin = None, None, None
         self.canv.saveState()
         for op, (sc,sr), (ec,er), weight, color, cap, dash, join, count, space in self._linecmds:
-            if type(sr) is type('') and sr.startswith('split'): continue
+            if isinstance(sr,basestring) and sr.startswith('split'): continue
             if sc < 0: sc = sc + self._ncols
             if ec < 0: ec = ec + self._ncols
             if sr < 0: sr = sr + self._nrows
@@ -1157,7 +1152,7 @@
         A = []
         # hack up the line commands
         for op, (sc,sr), (ec,er), weight, color, cap, dash, join, count, space in self._linecmds:
-            if type(sr)is type('') and sr.startswith('split'):
+            if isinstance(sr,basestring) and sr.startswith('split'):
                 A.append((op,(sc,sr), (ec,sr), weight, color, cap, dash, join, count, space))
                 if sr=='splitlast':
                     sr = er = n-1
@@ -1364,9 +1359,8 @@
 
         just = cellstyle.alignment
         valign = cellstyle.valign
-        n = type(cellval)
-        if n in _SeqTypes or isinstance(cellval,Flowable):
-            if not n in _SeqTypes: cellval = (cellval,)
+        if isinstance(cellval,(tuple,list,Flowable)):
+            if not isinstance(cellval,(tuple,list)): cellval = (cellval,)
             # we assume it's a list of Flowables
             W = []
             H = []