Commits

Manfred Moitzi committed 6c77857

moved all Python 3.x dependencies to utils.py

  • Participants
  • Parent commits 6bc1170

Comments (0)

Files changed (9)

File svgwrite/animate.py

 # Copyright (C) 2010, Manfred Moitzi
 # License: GPLv3
 
-# Python 3 adaption
-import sys
-PYTHON3 = sys.version_info[0] > 2
-if PYTHON3:
-    basestring = str
-# Python 3 adaption
-
 from svgwrite.base import BaseElement
 from svgwrite.mixins import XLink
-from svgwrite.utils import strlist
+from svgwrite.utils import strlist, is_string
 
 class Set(BaseElement, XLink):
     """ The **set** element provides a simple means of just setting the value
         :ref:`keySplines`, :ref:`from`, :ref:`to` and :ref:`by`.
         """
         if values is not None:
-            if not isinstance(values, basestring):
+            if not is_string(values):
                 values = strlist(values, ';')
             self['values'] = values
 

File svgwrite/base.py

 The **BaseElement** is the root for all SVG elements.
 """
 
-import sys
-PYTHON3 = sys.version_info[0] > 2
-if PYTHON3:
-    basestring = str
-    unicode = lambda value: str(value)
-
 import xml.etree.ElementTree as etree
 import copy
 
 from svgwrite.params import Parameter
-from svgwrite.utils import AutoID
-
+from svgwrite.utils import AutoID, to_unicode
 class BaseElement(object):
     """
     The **BaseElement** is the root for all SVG elements. The SVG attributes
                 self.validator.check_svg_type(value, 'number')
             if isinstance(value, float) and self.profile == 'tiny':
                 value = round(value, 4)
-        return unicode(value)
+        return to_unicode(value)
 
     def set_desc(self, title=None, desc=None):
         """ Insert a **title** and/or a **desc** element as first subelement.

File svgwrite/data/typechecker.py

 # Copyright (C) 2010, Manfred Moitzi
 # License: GPLv3
 
-# Python 3 adaption
 import sys
-PYTHON3 = sys.version_info[0] > 2
-if PYTHON3:
-    basestring = str
-# Python 3 adaption
-
 import re
 
 from svgwrite.data import pattern
 from svgwrite.data.colors import colornames
 from svgwrite.data.svgparser import TransformListParser, PathDataParser, AnimationTimingParser
+from svgwrite.utils import is_string
 
 def iterflatlist(values):
     """ Flatten nested *values*, returns an *iterator*. """
     for element in values:
-        if hasattr(element, "__iter__") and not isinstance(element, basestring):
+        if hasattr(element, "__iter__") and not is_string(element):
             for item in iterflatlist(element):
                 yield item
         else:
         #angle ::= number (~"deg" | ~"grad" | ~"rad")?
         if self.is_number(value):
             return True
-        elif isinstance(value, basestring):
+        elif is_string(value):
             return pattern.angle.match(value.strip()) is not None
         return False
 
         #frequency ::= number (~"Hz" | ~"kHz")
         if self.is_number(value):
             return True
-        elif isinstance(value, basestring):
+        elif is_string(value):
             return pattern.frequency.match(value.strip()) is not None
         return False
 
         # a more generalized complement to Uniform Resource Identifiers (URIs)
         # nearly everything can be a valid <IRI>
         # only a none-empty string ist a valid input
-        if isinstance(value, basestring):
+        if is_string(value):
             return bool(value.strip())
         else:
             return False
             return False
         if isinstance(value, (int, float)):
             return self.is_number(value)
-        elif isinstance(value, basestring):
+        elif is_string(value):
             result = pattern.length.match(value.strip())
             if result:
                 number, tmp, unit = result.groups()
             #TODO: improve split function!!!!
             if isinstance(value, (int, float)):
                 return (value, )
-            if isinstance(value, basestring):
+            if is_string(value):
                 return iterflatlist(v.split(',') for v in value.split(' '))
             return value
         #list-of-Ts ::= T
 
     def is_four_numbers(self, value):
         def split(value):
-            if isinstance(value, basestring):
+            if is_string(value):
                 values = iterflatlist( (v.strip().split(' ') for v in value.split(',')) )
                 return (v for v in values if v)
             else:
     def is_number_optional_number(self, value):
         #number-optional-number ::= number
         #                           | number comma-wsp number
-        if isinstance(value, basestring):
+        if is_string(value):
             values = re.split(' *,? *', value.strip())
             if 0 < len(values) < 3: # 1 or 2 numbers
                 for v in values:
         #percentage ::= number "%"
         if self.is_number(value):
             return True
-        elif isinstance(value, basestring):
+        elif is_string(value):
             return pattern.percentage.match(value.strip()) is not None
         return False
 
         #time ::= <number> (~"ms" | ~"s")?
         if self.is_number(value):
             return True
-        elif isinstance(value, basestring):
+        elif is_string(value):
             return pattern.time.match(value.strip()) is not None
         return False
 
     def is_transform_list(self, value):
-        if isinstance(value, basestring):
+        if is_string(value):
             return TransformListParser.is_valid(value)
         else:
             return False
 
     def is_path_data(self, value):
-        if isinstance(value, basestring):
+        if is_string(value):
             return PathDataParser.is_valid(value)
         else:
             return False
         return True
 
     def is_timing_value_list(self, value):
-        if isinstance(value, basestring):
+        if is_string(value):
             return AnimationTimingParser.is_valid(value)
         else:
             return False
     def is_boolean(self, value):
         if isinstance(value, bool):
             return True
-        if isinstance(value, basestring):
+        if is_string(value):
             return value.strip().lower() in ('true', 'false')
         return False
 

File svgwrite/filters.py

 
 from svgwrite.base import BaseElement
 from svgwrite.mixins import XLink, Presentation
-from svgwrite.utils import strlist
+from svgwrite.utils import strlist, is_string
 
 __all__ = ['Filter']
 
             self['width'] = size[0]
             self['height'] = size[1]
         if resolution is not None:
-            if isinstance(resolution, basestring):
+            if is_string(resolution):
                 self['filterRes'] = resolution
             elif hasattr(resolution, '__iter__'):
                 self['filterRes'] = strlist(resolution, ' ')

File svgwrite/gradients.py

 
 from svgwrite.base import BaseElement
 from svgwrite.mixins import Transform, XLink
+from svgwrite.utils import is_string
 
 class _GradientStop(BaseElement):
     elementname = 'stop'
     def __init__(self, inherit=None, **extra):
         super(_AbstractGradient, self).__init__(**extra)
         if inherit is not None:
-            if isinstance(inherit, basestring):
+            if is_string(inherit):
                 self.set_href(inherit)
             else:
                 self.set_href(inherit.get_iri())

File svgwrite/mixins.py

 # Copyright (C) 2010, Manfred Moitzi
 # License: GPLv3
 
-# Python 3 adaption
-import sys
-PYTHON3 = sys.version_info[0] > 2
-if PYTHON3:
-    basestring = str
-# Python 3 adaption
-
 from svgwrite.utils import strlist
 from svgwrite.base import Title, Desc
+from svgwrite.utils import is_string
 
 _horiz = {'center': 'xMid', 'left': 'xMin', 'right': 'xMax'}
 _vert  = {'middle': 'YMid', 'top': 'YMin', 'bottom':'YMax'}
     def update_id(self):
         if not hasattr(self, 'href'):
             return
-        if isinstance(self.href, basestring):
+        if is_string(self.href):
             idstr = self.href
         else:
             idstr = self.href.get_iri()
 
         """
         if color:
-            if isinstance(color, basestring):
+            if is_string(color):
                 self['fill'] = color
             else:
                 self['fill'] = color.get_paint_server()
         """
 
         if color:
-            if isinstance(color, basestring):
+            if is_string(color):
                 self['stroke'] = color
             else:
                 self['stroke'] = color.get_paint_server()
 
         """
         def get_funciri(value):
-            if isinstance(value, basestring):
+            if is_string(value):
                 # strings has to be a valid reference including the '#'
                 return 'url(%s)' % value
             else:
                 # else create a reference to the object '#id'
                 return 'url(#%s)' % value['id']
 
-        if isinstance(markers, basestring):
+        if is_string(markers):
             self['marker'] = get_funciri(markers)
         else:
             try:

File svgwrite/pattern.py

 
 from svgwrite.base import BaseElement
 from svgwrite.mixins import XLink, ViewBox, Transform, Presentation
+from svgwrite.utils import is_string
 
 class Pattern(BaseElement, XLink, ViewBox, Transform, Presentation):
     """
             self['width'] = size[0]
             self['height'] = size[1]
         if inherit is not None:
-            if isinstance(inherit, basestring):
+            if is_string(inherit):
                 self.set_href(inherit)
             else:
                 self.set_href(inherit.get_iri())

File svgwrite/text.py

 character data inside the **text** element.
 
 """
-# Python 3 adaption
-import sys
-PYTHON3 = sys.version_info[0] > 2
-if PYTHON3:
-    basestring = str
-    unicode = lambda value: str(value)
-# Python 3 adaption
 
 from svgwrite.base import BaseElement
 from svgwrite.mixins import Presentation, Transform, XLink
-from svgwrite.utils import iterflatlist, strlist
+from svgwrite.utils import iterflatlist, strlist, is_string, to_unicode
 
 class TSpan(BaseElement, Presentation):
     """
         super(TSpan, self).__init__(**extra)
         self.text = text
         if insert is not None:
-            if isinstance(insert, basestring):
+            if is_string(insert):
                 raise TypeError("'insert' should be a <tuple> or a <list>  with" \
                                 " at least two elements.")
             if x or y:
 
     def get_xml(self):
         xml = super(TSpan, self).get_xml()
-        xml.text = unicode(self.text)
+        xml.text = to_unicode(self.text)
         return xml
 
 class Text(TSpan, Transform):

File svgwrite/utils.py

 .. autofunction:: rect_top_left_corner
 
 """
+
+import sys
+PYTHON3 = sys.version_info[0] > 2
+
 # Python 3 adaption
-import sys
-if sys.version_info[0] > 2:
-    basestring = str
+def is_string(value):
+    if PYTHON3:
+        return isinstance(value, str)
+    else:
+        return isinstance(value, basestring)
+
+def to_unicode(value):
+    if PYTHON3:
+        return str(value)
+    else:
+        return unicode(value)
 # Python 3 adaption
 
 import re
 
 from svgwrite.data import pattern
 
+
 def rgb(r=0, g=0, b=0, mode='RGB'):
     """
     Convert **r**, **g**, **b** values to a `string`.
 
     """
     for element in values:
-        if hasattr(element, "__iter__") and not isinstance(element, basestring):
+        if hasattr(element, "__iter__") and not is_string(element):
             for item in iterflatlist(element):
                 yield item
         else:
     :returns: `string`
 
     """
-    if isinstance(values, basestring):
+    if is_string(values):
         return values
     else:
         return seperator.join([str(value) for value in iterflatlist(values) if value is not None])