[Zope3-checkins] SVN: Zope3/trunk/ Fixed zope.i18n.interpolate:

Dmitry Vasiliev dima at hlabs.spb.ru
Thu Jan 5 06:40:58 EST 2006


Log message for revision 41144:
  Fixed zope.i18n.interpolate:
  
    - now if the variable wasn't found in the mapping no substitution
      will happens.
  
    - fixed interpolation in case "$name $$name", only the first variable
      will be substituted.
  

Changed:
  U   Zope3/trunk/doc/CHANGES.txt
  U   Zope3/trunk/src/zope/i18n/__init__.py
  U   Zope3/trunk/src/zope/i18n/tests/test_interpolate.py
  U   Zope3/trunk/src/zope/i18n/translationdomain.py

-=-
Modified: Zope3/trunk/doc/CHANGES.txt
===================================================================
--- Zope3/trunk/doc/CHANGES.txt	2006-01-04 23:47:02 UTC (rev 41143)
+++ Zope3/trunk/doc/CHANGES.txt	2006-01-05 11:40:56 UTC (rev 41144)
@@ -21,10 +21,18 @@
     Restructuring
 
       - Removed unused menus and made previous titles, the description,
-	since they were awefully long. Then I created new, short titles.
+        since they were awefully long. Then I created new, short titles.
 
     Bug Fixes
 
+      - zope.i18n.interpolate:
+
+        + now if the variable wasn't found in the mapping no substitution
+          will happens.
+
+        + fixed interpolation in case "$name $$name", only the first variable
+          will be substituted.
+
       - Fixed storage bug reported, fixed and tested by Zhiyun (Simon) Hang.
 
       - Fixed a Gadfly DB Adapter bug that was reported, fixed and tested by
@@ -42,7 +50,7 @@
 
     Much thanks to everyone who contributed to this release:
 
-      Jim Fulton, Marius Gedminas, Brian Sutherland, Stephan Richter, Dimitry
+      Jim Fulton, Marius Gedminas, Brian Sutherland, Stephan Richter, Dmitry
       Vasiliev, Tim Peters, Zachery Bir, Gary Poster, Egon Frerich, Zhiyun
       (Simon) Hang, Tadashi Matsumoto, Simon Michael, Encople Degoute
 

Modified: Zope3/trunk/src/zope/i18n/__init__.py
===================================================================
--- Zope3/trunk/src/zope/i18n/__init__.py	2006-01-04 23:47:02 UTC (rev 41143)
+++ Zope3/trunk/src/zope/i18n/__init__.py	2006-01-05 11:40:56 UTC (rev 41144)
@@ -29,13 +29,14 @@
 from zope.i18n.interfaces import IFallbackTranslationDomainFactory
 from zope.component import queryUtility
 
+
 # Set up regular expressions for finding interpolation variables in text.
 # NAME_RE must exactly match the expression of the same name in the
 # zope.tal.taldefs module:
 NAME_RE = r"[a-zA-Z][-a-zA-Z0-9_]*"
 
-_interp_regex = re.compile(r'(?<!\$)(\$(?:%(n)s|{%(n)s}))' %({'n': NAME_RE}))
-_get_var_regex = re.compile(r'%(n)s' %({'n': NAME_RE}))
+_interp_regex = re.compile(r'(?<!\$)(\$(?:(%(n)s)|{(%(n)s)}))'
+    % ({'n': NAME_RE}))
 
 def _translate(msgid, domain=None, mapping=None, context=None,
                target_language=None, default=None):
@@ -74,24 +75,40 @@
         args = args[1:]
     return _translate(*args, **kw)
 
-def interpolate(text, mapping):
-    """Insert the data passed from mapping into the text"""
+def interpolate(text, mapping=None):
+    """Insert the data passed from mapping into the text.
 
-    # If no translation was found, there is nothing to do.
-    if text is None:
-        return None
+    First setup a test mapping:
 
-    # If the mapping does not exist, make a "raw translation" without
-    # interpolation.
-    if mapping is None:
-        return text
+    >>> mapping = {"name": "Zope", "version": 3}
 
-    # Find all the spots we want to substitute
-    to_replace = _interp_regex.findall(text)
+    In the text we can use substitution slots like $varname or ${varname}:
 
-    # Now substitute with the variables in mapping
-    for string in to_replace:
-        var = _get_var_regex.findall(string)[0]
-        text = text.replace(string, unicode(mapping.get(var)))
+    >>> interpolate(u"This is $name version ${version}.", mapping)
+    u'This is Zope version 3.'
 
-    return text
+    Interpolation variables can be used more than once in the text:
+
+    >>> interpolate(u"This is $name version ${version}. ${name} $version!",
+    ...             mapping)
+    u'This is Zope version 3. Zope 3!'
+
+    In case if the variable wasn't found in the mapping or '$$' form
+    was used no substitution will happens:
+
+    >>> interpolate(u"This is $name $version. $unknown $$name $${version}.",
+    ...             mapping)
+    u'This is Zope 3. $unknown $$name $${version}.'
+
+    >>> interpolate(u"This is ${name}")
+    u'This is ${name}'
+    """
+
+    def replace(match):
+        whole, param1, param2 = match.groups()
+        return unicode(mapping.get(param1 or param2, whole))
+
+    if not text or not mapping:
+        return text
+
+    return _interp_regex.sub(replace, text)

Modified: Zope3/trunk/src/zope/i18n/tests/test_interpolate.py
===================================================================
--- Zope3/trunk/src/zope/i18n/tests/test_interpolate.py	2006-01-04 23:47:02 UTC (rev 41143)
+++ Zope3/trunk/src/zope/i18n/tests/test_interpolate.py	2006-01-05 11:40:56 UTC (rev 41144)
@@ -11,49 +11,18 @@
 # FOR A PARTICULAR PURPOSE.
 #
 ##############################################################################
-"""This is an 'abstract' test for the ITranslationDomain interface.
+"""Tests for zope.i18n.interpolate.
 
 $Id$
 """
 import unittest
-from zope.i18n import interpolate
 
+from zope.testing import doctest
 
-class TestInterpolation(unittest.TestCase):
 
-    def testInterpolation(self):
-        mapping = {'name': 'Zope', 'version': '3x', 'number': 3}
-        # Test simple interpolations
-        self.assertEqual(
-            interpolate('This is $name.', mapping), 'This is Zope.')
-        self.assertEqual(
-            interpolate('This is ${name}.', mapping), 'This is Zope.')
-        # Test more than one interpolation variable
-        self.assertEqual(
-            interpolate('This is $name version $version.', mapping),
-            'This is Zope version 3x.')
-        self.assertEqual(
-            interpolate('This is ${name} version $version.', mapping),
-            'This is Zope version 3x.')
-        self.assertEqual(
-            interpolate('This is $name version ${version}.', mapping),
-            'This is Zope version 3x.')
-        self.assertEqual(
-            interpolate('This is ${name} version ${version}.', mapping),
-            'This is Zope version 3x.')
-        # Test escaping the $
-        self.assertEqual(
-            interpolate('This is $$name.', mapping), 'This is $$name.')
-        self.assertEqual(
-            interpolate('This is $${name}.', mapping), 'This is $${name}.')
-        # Test interpolation of non-string objects
-        self.assertEqual(interpolate('Number $number.', mapping), 'Number 3.')
-        
-
 def test_suite():
-    return unittest.TestSuite((
-        unittest.makeSuite(TestInterpolation),
-        ))
+    return doctest.DocTestSuite("zope.i18n")
 
+
 if __name__=='__main__':
     unittest.TextTestRunner().run(test_suite())

Modified: Zope3/trunk/src/zope/i18n/translationdomain.py
===================================================================
--- Zope3/trunk/src/zope/i18n/translationdomain.py	2006-01-04 23:47:02 UTC (rev 41143)
+++ Zope3/trunk/src/zope/i18n/translationdomain.py	2006-01-05 11:40:56 UTC (rev 41144)
@@ -119,7 +119,7 @@
                         break
 
         # Now we need to do the interpolation
-        if text is not None:
+        if text and mapping:
             text = interpolate(text, mapping)
         return text
 



More information about the Zope3-Checkins mailing list