changeset 43:0ad88be7da38

Load locale data lazily to avoid penalizing usage of `Locale` objects when no locale data is actually needed.
author cmlenz
date Wed, 06 Jun 2007 12:12:44 +0000
parents cf94e70a77f3
children 8551dbab118e
files babel/core.py babel/localedata.py
diffstat 2 files changed, 26 insertions(+), 6 deletions(-) [+]
line wrap: on
line diff
--- a/babel/core.py
+++ b/babel/core.py
@@ -85,10 +85,10 @@
         self.language = language
         self.territory = territory
         self.variant = variant
+        self.__data = None
+
         identifier = str(self)
-        try:
-            self._data = localedata.load(identifier)
-        except IOError:
+        if not localedata.exists(identifier):
             raise UnknownLocaleError(identifier)
 
     def default(cls, category=None):
@@ -142,13 +142,20 @@
         return '_'.join(filter(None, [self.language, self.territory,
                                       self.variant]))
 
+    def _data(self):
+        if self.__data is None:
+            self.__data = localedata.load(str(self))
+        return self.__data
+    _data = property(_data)
+
     def display_name(self):
         retval = self.languages.get(self.language)
         if self.territory:
             variant = ''
             if self.variant:
                 variant = ', %s' % self.variants.get(self.variant)
-            retval += ' (%s%s)' % (self.territories.get(self.territory), variant)
+            retval += ' (%s%s)' % (self.territories.get(self.territory),
+                                   variant)
         return retval
     display_name = property(display_name, doc="""\
         The localized display name of the locale.
@@ -157,6 +164,8 @@
         u'English'
         >>> Locale('en', 'US').display_name
         u'English (United States)'
+        >>> Locale('sv').display_name
+        u'svenska'
         
         :type: `unicode`
         """)
--- a/babel/localedata.py
+++ b/babel/localedata.py
@@ -30,6 +30,18 @@
 
 _cache = {}
 _cache_lock = threading.RLock()
+_dirname = os.path.join(os.path.dirname(__file__), 'localedata')
+
+def exists(name):
+    """Check whether locale data is available for the given locale.
+    
+    :param name: the locale identifier string
+    :return: `True` if the locale data exists, `False` otherwise
+    :rtype: `bool`
+    """
+    if name in _cache:
+        return True
+    return os.path.exists(os.path.join(_dirname, '%s.dat' % name))
 
 def load(name):
     """Load the locale data for the given locale.
@@ -70,8 +82,7 @@
                 else:
                     parent = '_'.join(parts[:-1])
                 data = load(parent).copy()
-            filename = os.path.join(os.path.dirname(__file__),
-                                    'localedata/%s.dat' % name)
+            filename = os.path.join(_dirname, '%s.dat' % name)
             fileobj = open(filename, 'rb')
             try:
                 if name != 'root':
Copyright (C) 2012-2017 Edgewall Software