cmlenz@61: # -*- coding: utf-8 -*- cmlenz@61: # cmlenz@61: # Copyright (C) 2007 Edgewall Software cmlenz@61: # All rights reserved. cmlenz@61: # cmlenz@61: # This software is licensed as described in the file COPYING, which cmlenz@61: # you should have received as part of this distribution. The terms cmlenz@61: # are also available at http://babel.edgewall.org/wiki/License. cmlenz@61: # cmlenz@61: # This software consists of voluntary contributions made by many cmlenz@61: # individuals. For the exact contribution history, see the revision cmlenz@61: # history and logs, available at http://babel.edgewall.org/log/. cmlenz@61: cmlenz@61: """Several classes and functions that help with integrating and using Babel cmlenz@61: in applications. cmlenz@61: cmlenz@61: .. note: the code in this module is not used by Babel itself cmlenz@61: """ cmlenz@61: cmlenz@101: from datetime import date, datetime, time cmlenz@61: import gettext cmlenz@61: cmlenz@101: from babel.core import Locale cmlenz@101: from babel.dates import format_date, format_datetime, format_time, LC_TIME cmlenz@101: from babel.numbers import format_number, format_decimal, format_currency, \ cmlenz@101: format_percent, format_scientific, LC_NUMERIC fschwarz@508: from babel.util import set, UTC cmlenz@101: cmlenz@101: __all__ = ['Format', 'LazyProxy', 'Translations'] cmlenz@61: __docformat__ = 'restructuredtext en' cmlenz@61: cmlenz@61: cmlenz@101: class Format(object): cmlenz@101: """Wrapper class providing the various date and number formatting functions cmlenz@101: bound to a specific locale and time-zone. cmlenz@101: cmlenz@101: >>> fmt = Format('en_US', UTC) cmlenz@101: >>> fmt.date(date(2007, 4, 1)) cmlenz@101: u'Apr 1, 2007' cmlenz@101: >>> fmt.decimal(1.2345) cmlenz@101: u'1.234' cmlenz@101: """ cmlenz@101: cmlenz@101: def __init__(self, locale, tzinfo=None): cmlenz@101: """Initialize the formatter. cmlenz@101: cmlenz@101: :param locale: the locale identifier or `Locale` instance cmlenz@101: :param tzinfo: the time-zone info (a `tzinfo` instance or `None`) cmlenz@101: """ cmlenz@101: self.locale = Locale.parse(locale) cmlenz@101: self.tzinfo = tzinfo cmlenz@101: cmlenz@101: def date(self, date=None, format='medium'): cmlenz@101: """Return a date formatted according to the given pattern. cmlenz@101: cmlenz@101: >>> fmt = Format('en_US') cmlenz@101: >>> fmt.date(date(2007, 4, 1)) cmlenz@101: u'Apr 1, 2007' cmlenz@101: cmlenz@101: :see: `babel.dates.format_date` cmlenz@101: """ cmlenz@101: return format_date(date, format, locale=self.locale) cmlenz@101: cmlenz@101: def datetime(self, datetime=None, format='medium'): cmlenz@101: """Return a date and time formatted according to the given pattern. cmlenz@101: cmlenz@101: >>> from pytz import timezone cmlenz@101: >>> fmt = Format('en_US', tzinfo=timezone('US/Eastern')) cmlenz@101: >>> fmt.datetime(datetime(2007, 4, 1, 15, 30)) cmlenz@101: u'Apr 1, 2007 11:30:00 AM' cmlenz@101: cmlenz@101: :see: `babel.dates.format_datetime` cmlenz@101: """ cmlenz@101: return format_datetime(datetime, format, tzinfo=self.tzinfo, cmlenz@101: locale=self.locale) cmlenz@101: cmlenz@101: def time(self, time=None, format='medium'): cmlenz@101: """Return a time formatted according to the given pattern. cmlenz@101: cmlenz@101: >>> from pytz import timezone cmlenz@101: >>> fmt = Format('en_US', tzinfo=timezone('US/Eastern')) cmlenz@349: >>> fmt.time(datetime(2007, 4, 1, 15, 30)) cmlenz@101: u'11:30:00 AM' cmlenz@101: cmlenz@101: :see: `babel.dates.format_time` cmlenz@101: """ cmlenz@101: return format_time(time, format, tzinfo=self.tzinfo, locale=self.locale) cmlenz@101: cmlenz@101: def number(self, number): cmlenz@101: """Return an integer number formatted for the locale. cmlenz@101: cmlenz@101: >>> fmt = Format('en_US') cmlenz@101: >>> fmt.number(1099) cmlenz@101: u'1,099' cmlenz@101: cmlenz@101: :see: `babel.numbers.format_number` cmlenz@101: """ cmlenz@101: return format_number(number, locale=self.locale) cmlenz@101: cmlenz@101: def decimal(self, number, format=None): cmlenz@101: """Return a decimal number formatted for the locale. cmlenz@101: cmlenz@101: >>> fmt = Format('en_US') cmlenz@101: >>> fmt.decimal(1.2345) cmlenz@101: u'1.234' cmlenz@101: cmlenz@101: :see: `babel.numbers.format_decimal` cmlenz@101: """ cmlenz@101: return format_decimal(number, format, locale=self.locale) cmlenz@101: cmlenz@101: def currency(self, number, currency): cmlenz@101: """Return a number in the given currency formatted for the locale. cmlenz@101: cmlenz@101: :see: `babel.numbers.format_currency` cmlenz@101: """ cmlenz@101: return format_currency(number, currency, locale=self.locale) cmlenz@101: cmlenz@101: def percent(self, number, format=None): cmlenz@101: """Return a number formatted as percentage for the locale. cmlenz@101: cmlenz@101: >>> fmt = Format('en_US') cmlenz@101: >>> fmt.percent(0.34) cmlenz@101: u'34%' cmlenz@101: cmlenz@101: :see: `babel.numbers.format_percent` cmlenz@101: """ cmlenz@101: return format_percent(number, format, locale=self.locale) cmlenz@101: cmlenz@101: def scientific(self, number): cmlenz@101: """Return a number formatted using scientific notation for the locale. cmlenz@101: cmlenz@101: :see: `babel.numbers.format_scientific` cmlenz@101: """ cmlenz@101: return format_scientific(number, locale=self.locale) cmlenz@101: cmlenz@101: cmlenz@61: class LazyProxy(object): cmlenz@61: """Class for proxy objects that delegate to a specified function to evaluate cmlenz@61: the actual object. cmlenz@61: cmlenz@61: >>> def greeting(name='world'): cmlenz@61: ... return 'Hello, %s!' % name cmlenz@61: >>> lazy_greeting = LazyProxy(greeting, name='Joe') cmlenz@61: >>> print lazy_greeting cmlenz@61: Hello, Joe! cmlenz@61: >>> u' ' + lazy_greeting cmlenz@61: u' Hello, Joe!' cmlenz@61: >>> u'(%s)' % lazy_greeting cmlenz@61: u'(Hello, Joe!)' cmlenz@61: cmlenz@61: This can be used, for example, to implement lazy translation functions that cmlenz@61: delay the actual translation until the string is actually used. The cmlenz@61: rationale for such behavior is that the locale of the user may not always cmlenz@61: be available. In web applications, you only know the locale when processing cmlenz@61: a request. cmlenz@61: cmlenz@61: The proxy implementation attempts to be as complete as possible, so that cmlenz@61: the lazy objects should mostly work as expected, for example for sorting: cmlenz@61: cmlenz@61: >>> greetings = [ cmlenz@61: ... LazyProxy(greeting, 'world'), cmlenz@61: ... LazyProxy(greeting, 'Joe'), cmlenz@61: ... LazyProxy(greeting, 'universe'), cmlenz@61: ... ] cmlenz@61: >>> greetings.sort() cmlenz@61: >>> for greeting in greetings: cmlenz@61: ... print greeting cmlenz@61: Hello, Joe! cmlenz@61: Hello, universe! cmlenz@61: Hello, world! cmlenz@61: """ cmlenz@61: __slots__ = ['_func', '_args', '_kwargs', '_value'] cmlenz@61: cmlenz@61: def __init__(self, func, *args, **kwargs): cmlenz@61: # Avoid triggering our own __setattr__ implementation cmlenz@61: object.__setattr__(self, '_func', func) cmlenz@61: object.__setattr__(self, '_args', args) cmlenz@61: object.__setattr__(self, '_kwargs', kwargs) cmlenz@61: object.__setattr__(self, '_value', None) cmlenz@61: cmlenz@61: def value(self): cmlenz@61: if self._value is None: cmlenz@61: value = self._func(*self._args, **self._kwargs) cmlenz@61: object.__setattr__(self, '_value', value) cmlenz@61: return self._value cmlenz@61: value = property(value) cmlenz@61: cmlenz@61: def __contains__(self, key): cmlenz@61: return key in self.value cmlenz@61: cmlenz@61: def __nonzero__(self): cmlenz@61: return bool(self.value) cmlenz@61: cmlenz@61: def __dir__(self): cmlenz@61: return dir(self.value) cmlenz@61: cmlenz@61: def __iter__(self): cmlenz@61: return iter(self.value) cmlenz@61: cmlenz@61: def __len__(self): cmlenz@61: return len(self.value) cmlenz@61: cmlenz@61: def __str__(self): cmlenz@61: return str(self.value) cmlenz@61: cmlenz@61: def __unicode__(self): cmlenz@61: return unicode(self.value) cmlenz@61: cmlenz@61: def __add__(self, other): cmlenz@61: return self.value + other cmlenz@61: cmlenz@61: def __radd__(self, other): cmlenz@61: return other + self.value cmlenz@61: cmlenz@61: def __mod__(self, other): cmlenz@61: return self.value % other cmlenz@61: cmlenz@61: def __rmod__(self, other): cmlenz@61: return other % self.value cmlenz@61: cmlenz@61: def __mul__(self, other): cmlenz@61: return self.value * other cmlenz@61: cmlenz@61: def __rmul__(self, other): cmlenz@61: return other * self.value cmlenz@61: cmlenz@61: def __call__(self, *args, **kwargs): cmlenz@61: return self.value(*args, **kwargs) cmlenz@61: cmlenz@61: def __lt__(self, other): cmlenz@61: return self.value < other cmlenz@61: cmlenz@61: def __le__(self, other): cmlenz@61: return self.value <= other cmlenz@61: cmlenz@61: def __eq__(self, other): cmlenz@61: return self.value == other cmlenz@61: cmlenz@61: def __ne__(self, other): cmlenz@61: return self.value != other cmlenz@61: cmlenz@61: def __gt__(self, other): cmlenz@61: return self.value > other cmlenz@61: cmlenz@61: def __ge__(self, other): cmlenz@61: return self.value >= other cmlenz@61: cmlenz@61: def __delattr__(self, name): cmlenz@61: delattr(self.value, name) cmlenz@61: cmlenz@61: def __getattr__(self, name): cmlenz@61: return getattr(self.value, name) cmlenz@61: pjenvey@100: def __setattr__(self, name, value): cmlenz@61: setattr(self.value, name, value) cmlenz@61: cmlenz@61: def __delitem__(self, key): cmlenz@61: del self.value[key] cmlenz@61: cmlenz@61: def __getitem__(self, key): cmlenz@61: return self.value[key] cmlenz@61: cmlenz@61: def __setitem__(self, key, value): pjenvey@100: self.value[key] = value cmlenz@61: cmlenz@407: cmlenz@407: class Translations(gettext.GNUTranslations, object): cmlenz@61: """An extended translation catalog class.""" cmlenz@61: cmlenz@61: DEFAULT_DOMAIN = 'messages' cmlenz@61: cmlenz@413: def __init__(self, fileobj=None, domain=DEFAULT_DOMAIN): cmlenz@61: """Initialize the translations catalog. cmlenz@413: cmlenz@61: :param fileobj: the file-like object the translation should be read cmlenz@61: from cmlenz@61: """ cmlenz@61: gettext.GNUTranslations.__init__(self, fp=fileobj) cmlenz@346: self.files = filter(None, [getattr(fileobj, 'name', None)]) cmlenz@413: self.domain = domain cmlenz@413: self._domains = {} cmlenz@61: cmlenz@61: def load(cls, dirname=None, locales=None, domain=DEFAULT_DOMAIN): cmlenz@61: """Load translations from the given directory. cmlenz@413: cmlenz@61: :param dirname: the directory containing the ``MO`` files cmlenz@61: :param locales: the list of locales in order of preference (items in cmlenz@61: this list can be either `Locale` objects or locale cmlenz@61: strings) cmlenz@61: :param domain: the message domain cmlenz@61: :return: the loaded catalog, or a ``NullTranslations`` instance if no cmlenz@61: matching translations were found cmlenz@61: :rtype: `Translations` cmlenz@61: """ cmlenz@346: if locales is not None: cmlenz@346: if not isinstance(locales, (list, tuple)): cmlenz@346: locales = [locales] cmlenz@346: locales = [str(locale) for locale in locales] cmlenz@413: if not domain: cmlenz@413: domain = cls.DEFAULT_DOMAIN cmlenz@413: filename = gettext.find(domain, dirname, locales) cmlenz@61: if not filename: cmlenz@61: return gettext.NullTranslations() cmlenz@413: return cls(fileobj=open(filename, 'rb'), domain=domain) cmlenz@61: load = classmethod(load) cmlenz@61: cmlenz@413: def __repr__(self): cmlenz@413: return '<%s: "%s">' % (type(self).__name__, cmlenz@413: self._info.get('project-id-version')) cmlenz@413: cmlenz@413: def add(self, translations, merge=True): cmlenz@413: """Add the given translations to the catalog. cmlenz@413: cmlenz@413: If the domain of the translations is different than that of the cmlenz@413: current catalog, they are added as a catalog that is only accessible cmlenz@413: by the various ``d*gettext`` functions. cmlenz@413: cmlenz@413: :param translations: the `Translations` instance with the messages to cmlenz@413: add cmlenz@413: :param merge: whether translations for message domains that have cmlenz@413: already been added should be merged with the existing cmlenz@413: translations cmlenz@413: :return: the `Translations` instance (``self``) so that `merge` calls cmlenz@413: can be easily chained cmlenz@413: :rtype: `Translations` cmlenz@413: """ cmlenz@413: domain = getattr(translations, 'domain', self.DEFAULT_DOMAIN) cmlenz@413: if merge and domain == self.domain: cmlenz@413: return self.merge(translations) cmlenz@413: cmlenz@413: existing = self._domains.get(domain) cmlenz@413: if merge and existing is not None: cmlenz@413: existing.merge(translations) cmlenz@413: else: cmlenz@413: translations.add_fallback(self) cmlenz@413: self._domains[domain] = translations cmlenz@413: cmlenz@413: return self cmlenz@413: cmlenz@61: def merge(self, translations): cmlenz@61: """Merge the given translations into the catalog. cmlenz@413: cmlenz@413: Message translations in the specified catalog override any messages cmlenz@413: with the same identifier in the existing catalog. cmlenz@413: cmlenz@61: :param translations: the `Translations` instance with the messages to cmlenz@61: merge cmlenz@61: :return: the `Translations` instance (``self``) so that `merge` calls cmlenz@61: can be easily chained cmlenz@61: :rtype: `Translations` cmlenz@61: """ cmlenz@413: if isinstance(translations, gettext.GNUTranslations): cmlenz@61: self._catalog.update(translations._catalog) cmlenz@413: if isinstance(translations, Translations): cmlenz@413: self.files.extend(translations.files) cmlenz@413: cmlenz@61: return self cmlenz@61: cmlenz@413: def dgettext(self, domain, message): cmlenz@413: """Like ``gettext()``, but look the message up in the specified cmlenz@413: domain. cmlenz@413: """ cmlenz@413: return self._domains.get(domain, self).gettext(message) cmlenz@413: cmlenz@413: def ldgettext(self, domain, message): cmlenz@413: """Like ``lgettext()``, but look the message up in the specified cmlenz@413: domain. cmlenz@413: """ cmlenz@413: return self._domains.get(domain, self).lgettext(message) cmlenz@413: cmlenz@413: def dugettext(self, domain, message): cmlenz@413: """Like ``ugettext()``, but look the message up in the specified cmlenz@413: domain. cmlenz@413: """ cmlenz@413: return self._domains.get(domain, self).ugettext(message) cmlenz@413: cmlenz@413: def dngettext(self, domain, singular, plural, num): cmlenz@413: """Like ``ngettext()``, but look the message up in the specified cmlenz@413: domain. cmlenz@413: """ cmlenz@413: return self._domains.get(domain, self).ngettext(singular, plural, num) cmlenz@413: cmlenz@413: def ldngettext(self, domain, singular, plural, num): cmlenz@413: """Like ``lngettext()``, but look the message up in the specified cmlenz@413: domain. cmlenz@413: """ cmlenz@413: return self._domains.get(domain, self).lngettext(singular, plural, num) cmlenz@413: cmlenz@413: def dungettext(self, domain, singular, plural, num): cmlenz@413: """Like ``ungettext()`` but look the message up in the specified cmlenz@413: domain. cmlenz@413: """ cmlenz@413: return self._domains.get(domain, self).ungettext(singular, plural, num)