summaryrefslogtreecommitdiff
path: root/babel
diff options
context:
space:
mode:
authorArmin Ronacher <armin.ronacher@active-4.com>2013-07-05 12:12:27 +0200
committerArmin Ronacher <armin.ronacher@active-4.com>2013-07-05 12:12:27 +0200
commit588d1f8b711744c8d90dcbf6189866ce5ab76426 (patch)
treec92c275e0795620f1c0aa4476de884544bec6405 /babel
parent03217d2fcfdb9177e4c7cacedc623eb07da979a1 (diff)
downloadbabel-588d1f8b711744c8d90dcbf6189866ce5ab76426.tar.gz
Removed trailing whitespace
Diffstat (limited to 'babel')
-rw-r--r--babel/core.py286
-rw-r--r--babel/dates.py144
-rw-r--r--babel/localedata.py24
-rw-r--r--babel/messages/catalog.py2
-rw-r--r--babel/messages/extract.py2
-rwxr-xr-xbabel/messages/frontend.py6
-rw-r--r--babel/messages/mofile.py12
-rw-r--r--babel/messages/tests/catalog.py18
-rw-r--r--babel/messages/tests/frontend.py38
-rw-r--r--babel/messages/tests/pofile.py16
-rw-r--r--babel/numbers.py100
-rw-r--r--babel/plural.py2
-rw-r--r--babel/support.py70
-rw-r--r--babel/tests/core.py24
-rw-r--r--babel/tests/dates.py4
-rw-r--r--babel/tests/numbers.py84
-rw-r--r--babel/tests/support.py20
-rw-r--r--babel/util.py22
18 files changed, 437 insertions, 437 deletions
diff --git a/babel/core.py b/babel/core.py
index 31cfec0..e3f422e 100644
--- a/babel/core.py
+++ b/babel/core.py
@@ -26,15 +26,15 @@ _global_data = None
def get_global(key):
"""Return the dictionary for the given key in the global data.
-
+
The global data is stored in the ``babel/global.dat`` file and contains
information independent of individual locales.
-
+
>>> get_global('zone_aliases')['UTC']
'Etc/GMT'
>>> get_global('zone_territories')['Europe/Berlin']
'DE'
-
+
:param key: the data key
:return: the dictionary found in the global data under the given key
:rtype: `dict`
@@ -53,13 +53,13 @@ def get_global(key):
LOCALE_ALIASES = {
- 'ar': 'ar_SY', 'bg': 'bg_BG', 'bs': 'bs_BA', 'ca': 'ca_ES', 'cs': 'cs_CZ',
- 'da': 'da_DK', 'de': 'de_DE', 'el': 'el_GR', 'en': 'en_US', 'es': 'es_ES',
- 'et': 'et_EE', 'fa': 'fa_IR', 'fi': 'fi_FI', 'fr': 'fr_FR', 'gl': 'gl_ES',
- 'he': 'he_IL', 'hu': 'hu_HU', 'id': 'id_ID', 'is': 'is_IS', 'it': 'it_IT',
- 'ja': 'ja_JP', 'km': 'km_KH', 'ko': 'ko_KR', 'lt': 'lt_LT', 'lv': 'lv_LV',
- 'mk': 'mk_MK', 'nl': 'nl_NL', 'nn': 'nn_NO', 'no': 'nb_NO', 'pl': 'pl_PL',
- 'pt': 'pt_PT', 'ro': 'ro_RO', 'ru': 'ru_RU', 'sk': 'sk_SK', 'sl': 'sl_SI',
+ 'ar': 'ar_SY', 'bg': 'bg_BG', 'bs': 'bs_BA', 'ca': 'ca_ES', 'cs': 'cs_CZ',
+ 'da': 'da_DK', 'de': 'de_DE', 'el': 'el_GR', 'en': 'en_US', 'es': 'es_ES',
+ 'et': 'et_EE', 'fa': 'fa_IR', 'fi': 'fi_FI', 'fr': 'fr_FR', 'gl': 'gl_ES',
+ 'he': 'he_IL', 'hu': 'hu_HU', 'id': 'id_ID', 'is': 'is_IS', 'it': 'it_IT',
+ 'ja': 'ja_JP', 'km': 'km_KH', 'ko': 'ko_KR', 'lt': 'lt_LT', 'lv': 'lv_LV',
+ 'mk': 'mk_MK', 'nl': 'nl_NL', 'nn': 'nn_NO', 'no': 'nb_NO', 'pl': 'pl_PL',
+ 'pt': 'pt_PT', 'ro': 'ro_RO', 'ru': 'ru_RU', 'sk': 'sk_SK', 'sl': 'sl_SI',
'sv': 'sv_SE', 'th': 'th_TH', 'tr': 'tr_TR', 'uk': 'uk_UA'
}
@@ -71,7 +71,7 @@ class UnknownLocaleError(Exception):
def __init__(self, identifier):
"""Create the exception.
-
+
:param identifier: the identifier string of the unsupported locale
"""
Exception.__init__(self, 'unknown locale %r' % identifier)
@@ -80,45 +80,45 @@ class UnknownLocaleError(Exception):
class Locale(object):
"""Representation of a specific locale.
-
+
>>> locale = Locale('en', 'US')
>>> repr(locale)
"Locale('en', territory='US')"
>>> locale.display_name
u'English (United States)'
-
+
A `Locale` object can also be instantiated from a raw locale string:
-
+
>>> locale = Locale.parse('en-US', sep='-')
>>> repr(locale)
"Locale('en', territory='US')"
-
+
`Locale` objects provide access to a collection of locale data, such as
territory and language names, number and date format patterns, and more:
-
+
>>> locale.number_symbols['decimal']
u'.'
-
+
If a locale is requested for which no locale data is available, an
`UnknownLocaleError` is raised:
-
+
>>> Locale.parse('en_DE')
Traceback (most recent call last):
...
UnknownLocaleError: unknown locale 'en_DE'
-
+
:see: `IETF RFC 3066 <http://www.ietf.org/rfc/rfc3066.txt>`_
"""
def __init__(self, language, territory=None, script=None, variant=None):
"""Initialize the locale object from the given identifier components.
-
+
>>> locale = Locale('en', 'US')
>>> locale.language
'en'
>>> locale.territory
'US'
-
+
:param language: the language code
:param territory: the territory (country or region) code
:param script: the script code
@@ -131,7 +131,7 @@ class Locale(object):
self.script = script
self.variant = variant
self.__data = None
-
+
identifier = str(self)
if not localedata.exists(identifier):
raise UnknownLocaleError(identifier)
@@ -139,7 +139,7 @@ class Locale(object):
@classmethod
def default(cls, category=None, aliases=LOCALE_ALIASES):
"""Return the system default locale for the specified category.
-
+
>>> for name in ['LANGUAGE', 'LC_ALL', 'LC_CTYPE']:
... os.environ[name] = ''
>>> os.environ['LANG'] = 'fr_FR.UTF-8'
@@ -159,20 +159,20 @@ class Locale(object):
@classmethod
def negotiate(cls, preferred, available, sep='_', aliases=LOCALE_ALIASES):
"""Find the best match between available and requested locale strings.
-
+
>>> Locale.negotiate(['de_DE', 'en_US'], ['de_DE', 'de_AT'])
Locale('de', territory='DE')
>>> Locale.negotiate(['de_DE', 'en_US'], ['en', 'de'])
Locale('de')
>>> Locale.negotiate(['de_DE', 'de'], ['en_US'])
-
+
You can specify the character used in the locale identifiers to separate
the differnet components. This separator is applied to both lists. Also,
case is ignored in the comparison:
-
+
>>> Locale.negotiate(['de-DE', 'de'], ['en-us', 'de-de'], sep='-')
Locale('de', territory='DE')
-
+
:param preferred: the list of locale identifers preferred by the user
:param available: the list of locale identifiers available
:param aliases: a dictionary of aliases for locale identifiers
@@ -189,17 +189,17 @@ class Locale(object):
@classmethod
def parse(cls, identifier, sep='_'):
"""Create a `Locale` instance for the given locale identifier.
-
+
>>> l = Locale.parse('de-DE', sep='-')
>>> l.display_name
u'Deutsch (Deutschland)'
-
+
If the `identifier` parameter is not a string, but actually a `Locale`
object, that object is returned:
-
+
>>> Locale.parse(l)
Locale('de', territory='DE')
-
+
:param identifier: the locale identifier string
:param sep: optional component separator
:return: a corresponding `Locale` instance
@@ -247,13 +247,13 @@ class Locale(object):
def get_display_name(self, locale=None):
"""Return the display name of the locale using the given locale.
-
+
The display name will include the language, territory, script, and
variant, if those are specified.
-
+
>>> Locale('zh', 'CN', script='Hans').get_display_name('en')
u'Chinese (Simplified, China)'
-
+
:param locale: the locale to use
:return: the display name
"""
@@ -276,326 +276,326 @@ class Locale(object):
display_name = property(get_display_name, doc="""\
The localized display name of the locale.
-
+
>>> Locale('en').display_name
u'English'
>>> Locale('en', 'US').display_name
u'English (United States)'
>>> Locale('sv').display_name
u'svenska'
-
+
:type: `unicode`
""")
- @property
+ @property
def english_name(self):
"""The english display name of the locale.
-
+
>>> Locale('de').english_name
u'German'
>>> Locale('de', 'DE').english_name
u'German (Germany)'
-
+
:type: `unicode`"""
return self.get_display_name(Locale('en'))
#{ General Locale Display Names
- @property
+ @property
def languages(self):
"""Mapping of language codes to translated language names.
-
+
>>> Locale('de', 'DE').languages['ja']
u'Japanisch'
-
+
:type: `dict`
:see: `ISO 639 <http://www.loc.gov/standards/iso639-2/>`_"""
return self._data['languages']
- @property
+ @property
def scripts(self):
"""Mapping of script codes to translated script names.
-
+
>>> Locale('en', 'US').scripts['Hira']
u'Hiragana'
-
+
:type: `dict`
:see: `ISO 15924 <http://www.evertype.com/standards/iso15924/>`_"""
return self._data['scripts']
- @property
+ @property
def territories(self):
"""Mapping of script codes to translated script names.
-
+
>>> Locale('es', 'CO').territories['DE']
u'Alemania'
-
+
:type: `dict`
:see: `ISO 3166 <http://www.iso.org/iso/en/prods-services/iso3166ma/>`_"""
return self._data['territories']
- @property
+ @property
def variants(self):
"""Mapping of script codes to translated script names.
-
+
>>> Locale('de', 'DE').variants['1901']
u'Alte deutsche Rechtschreibung'
-
+
:type: `dict`"""
return self._data['variants']
#{ Number Formatting
- @property
+ @property
def currencies(self):
"""Mapping of currency codes to translated currency names.
-
+
>>> Locale('en').currencies['COP']
u'Colombian Peso'
>>> Locale('de', 'DE').currencies['COP']
u'Kolumbianischer Peso'
-
+
:type: `dict`"""
return self._data['currency_names']
- @property
+ @property
def currency_symbols(self):
"""Mapping of currency codes to symbols.
-
+
>>> Locale('en', 'US').currency_symbols['USD']
u'$'
>>> Locale('es', 'CO').currency_symbols['USD']
u'US$'
-
+
:type: `dict`"""
return self._data['currency_symbols']
- @property
+ @property
def number_symbols(self):
"""Symbols used in number formatting.
-
+
>>> Locale('fr', 'FR').number_symbols['decimal']
u','
-
+
:type: `dict`"""
return self._data['number_symbols']
- @property
+ @property
def decimal_formats(self):
"""Locale patterns for decimal number formatting.
-
+
>>> Locale('en', 'US').decimal_formats[None]
<NumberPattern u'#,##0.###'>
-
+
:type: `dict`"""
return self._data['decimal_formats']
- @property
+ @property
def currency_formats(self):
"""Locale patterns for currency number formatting.
-
+
>>> print Locale('en', 'US').currency_formats[None]
<NumberPattern u'\\xa4#,##0.00'>
-
+
:type: `dict`"""
return self._data['currency_formats']
- @property
+ @property
def percent_formats(self):
"""Locale patterns for percent number formatting.
-
+
>>> Locale('en', 'US').percent_formats[None]
<NumberPattern u'#,##0%'>
-
+
:type: `dict`"""
return self._data['percent_formats']
- @property
+ @property
def scientific_formats(self):
"""Locale patterns for scientific number formatting.
-
+
>>> Locale('en', 'US').scientific_formats[None]
<NumberPattern u'#E0'>
-
+
:type: `dict`"""
return self._data['scientific_formats']
#{ Calendar Information and Date Formatting
- @property
+ @property
def periods(self):
"""Locale display names for day periods (AM/PM).
-
+
>>> Locale('en', 'US').periods['am']
u'AM'
-
+
:type: `dict`"""
return self._data['periods']
- @property
+ @property
def days(self):
"""Locale display names for weekdays.
-
+
>>> Locale('de', 'DE').days['format']['wide'][3]
u'Donnerstag'
-
+
:type: `dict`"""
return self._data['days']
- @property
+ @property
def months(self):
"""Locale display names for months.
-
+
>>> Locale('de', 'DE').months['format']['wide'][10]
u'Oktober'
-
+
:type: `dict`"""
return self._data['months']
- @property
+ @property
def quarters(self):
"""Locale display names for quarters.
-
+
>>> Locale('de', 'DE').quarters['format']['wide'][1]
u'1. Quartal'
-
+
:type: `dict`"""
return self._data['quarters']
- @property
+ @property
def eras(self):
"""Locale display names for eras.
-
+
>>> Locale('en', 'US').eras['wide'][1]
u'Anno Domini'
>>> Locale('en', 'US').eras['abbreviated'][0]
u'BC'
-
+
:type: `dict`"""
return self._data['eras']
- @property
+ @property
def time_zones(self):
"""Locale display names for time zones.
-
+
>>> Locale('en', 'US').time_zones['Europe/London']['long']['daylight']
u'British Summer Time'
>>> Locale('en', 'US').time_zones['America/St_Johns']['city']
u'St. John\u2019s'
-
+
:type: `dict`"""
return self._data['time_zones']
- @property
+ @property
def meta_zones(self):
"""Locale display names for meta time zones.
-
+
Meta time zones are basically groups of different Olson time zones that
have the same GMT offset and daylight savings time.
-
+
>>> Locale('en', 'US').meta_zones['Europe_Central']['long']['daylight']
u'Central European Summer Time'
-
+
:type: `dict`
:since: version 0.9"""
return self._data['meta_zones']
- @property
+ @property
def zone_formats(self):
"""Patterns related to the formatting of time zones.
-
+
>>> Locale('en', 'US').zone_formats['fallback']
u'%(1)s (%(0)s)'
>>> Locale('pt', 'BR').zone_formats['region']
u'Hor\\xe1rio %s'
-
+
:type: `dict`
:since: version 0.9"""
return self._data['zone_formats']
- @property
+ @property
def first_week_day(self):
"""The first day of a week, with 0 being Monday.
-
+
>>> Locale('de', 'DE').first_week_day
0
>>> Locale('en', 'US').first_week_day
6
-
+
:type: `int`"""
return self._data['week_data']['first_day']
- @property
+ @property
def weekend_start(self):
"""The day the weekend starts, with 0 being Monday.
-
+
>>> Locale('de', 'DE').weekend_start
5
-
+
:type: `int`"""
return self._data['week_data']['weekend_start']
- @property
+ @property
def weekend_end(self):
"""The day the weekend ends, with 0 being Monday.
-
+
>>> Locale('de', 'DE').weekend_end
6
-
+
:type: `int`"""
return self._data['week_data']['weekend_end']
- @property
+ @property
def min_week_days(self):
- """The minimum number of days in a week so that the week is counted as
+ """The minimum number of days in a week so that the week is counted as
the first week of a year or month.
-
+
>>> Locale('de', 'DE').min_week_days
4
-
+
:type: `int`"""
return self._data['week_data']['min_days']
- @property
+ @property
def date_formats(self):
"""Locale patterns for date formatting.
-
+
>>> Locale('en', 'US').date_formats['short']
<DateTimePattern u'M/d/yy'>
>>> Locale('fr', 'FR').date_formats['long']
<DateTimePattern u'd MMMM y'>
-
+
:type: `dict`"""
return self._data['date_formats']
- @property
+ @property
def time_formats(self):
"""Locale patterns for time formatting.
-
+
>>> Locale('en', 'US').time_formats['short']
<DateTimePattern u'h:mm a'>
>>> Locale('fr', 'FR').time_formats['long']
<DateTimePattern u'HH:mm:ss z'>
-
+
:type: `dict`"""
return self._data['time_formats']
- @property
+ @property
def datetime_formats(self):
"""Locale patterns for datetime formatting.
-
+
>>> Locale('en').datetime_formats['full']
u"{1} 'at' {0}"
>>> Locale('th').datetime_formats['medium']
u'{1}, {0}'
-
+
:type: `dict`"""
return self._data['datetime_formats']
- @property
+ @property
def plural_form(self):
"""Plural rules for the locale.
-
+
>>> Locale('en').plural_form(1)
'one'
>>> Locale('en').plural_form(0)
@@ -604,7 +604,7 @@ class Locale(object):
'one'
>>> Locale('ru').plural_form(100)
'many'
-
+
:type: `PluralRule`"""
return self._data['plural_form']
@@ -612,7 +612,7 @@ class Locale(object):
def default_locale(category=None, aliases=LOCALE_ALIASES):
"""Returns the system default locale for a given category, based on
environment variables.
-
+
>>> for name in ['LANGUAGE', 'LC_ALL', 'LC_CTYPE']:
... os.environ[name] = ''
>>> os.environ['LANG'] = 'fr_FR.UTF-8'
@@ -651,21 +651,21 @@ def default_locale(category=None, aliases=LOCALE_ALIASES):
def negotiate_locale(preferred, available, sep='_', aliases=LOCALE_ALIASES):
"""Find the best match between available and requested locale strings.
-
+
>>> negotiate_locale(['de_DE', 'en_US'], ['de_DE', 'de_AT'])
'de_DE'
>>> negotiate_locale(['de_DE', 'en_US'], ['en', 'de'])
'de'
-
+
Case is ignored by the algorithm, the result uses the case of the preferred
locale identifier:
-
+
>>> negotiate_locale(['de_DE', 'en_US'], ['de_de', 'de_at'])
'de_DE'
-
+
>>> negotiate_locale(['de_DE', 'en_US'], ['de_de', 'de_at'])
'de_DE'
-
+
By default, some web browsers unfortunately do not include the territory
in the locale identifier for many locales, and some don't even allow the
user to easily add the territory. So while you may prefer using qualified
@@ -673,22 +673,22 @@ def negotiate_locale(preferred, available, sep='_', aliases=LOCALE_ALIASES):
the language-only locale sent by such browsers. To workaround that, this
function uses a default mapping of commonly used langauge-only locale
identifiers to identifiers including the territory:
-
+
>>> negotiate_locale(['ja', 'en_US'], ['ja_JP', 'en_US'])
'ja_JP'
-
+
Some browsers even use an incorrect or outdated language code, such as "no"
for Norwegian, where the correct locale identifier would actually be "nb_NO"
(Bokmål) or "nn_NO" (Nynorsk). The aliases are intended to take care of
such cases, too:
-
+
>>> negotiate_locale(['no', 'sv'], ['nb_NO', 'sv_SE'])
'nb_NO'
-
+
You can override this default mapping by passing a different `aliases`
dictionary to this function, or you can bypass the behavior althogher by
setting the `aliases` parameter to `None`.
-
+
:param preferred: the list of locale strings preferred by the user
:param available: the list of locale strings available
:param sep: character that separates the different parts of the locale
@@ -716,37 +716,37 @@ def negotiate_locale(preferred, available, sep='_', aliases=LOCALE_ALIASES):
def parse_locale(identifier, sep='_'):
"""Parse a locale identifier into a tuple of the form::
-
+
``(language, territory, script, variant)``
-
+
>>> parse_locale('zh_CN')
('zh', 'CN', None, None)
>>> parse_locale('zh_Hans_CN')
('zh', 'CN', 'Hans', None)
-
+
The default component separator is "_", but a different separator can be
specified using the `sep` parameter:
-
+
>>> parse_locale('zh-CN', sep='-')
('zh', 'CN', None, None)
-
+
If the identifier cannot be parsed into a locale, a `ValueError` exception
is raised:
-
+
>>> parse_locale('not_a_LOCALE_String')
Traceback (most recent call last):
...
ValueError: 'not_a_LOCALE_String' is not a valid locale identifier
-
+
Encoding information and locale modifiers are removed from the identifier:
-
+
>>> parse_locale('it_IT@euro')
('it', 'IT', None, None)
>>> parse_locale('en_US.UTF-8')
('en', 'US', None, None)
>>> parse_locale('de_DE.iso885915@euro')
('de', 'DE', None, None)
-
+
:param identifier: the locale identifier string
:param sep: character that separates the different components of the locale
identifier
@@ -754,7 +754,7 @@ def parse_locale(identifier, sep='_'):
:rtype: `tuple`
:raise `ValueError`: if the string does not appear to be a valid locale
identifier
-
+
:see: `IETF RFC 4646 <http://www.ietf.org/rfc/rfc4646.txt>`_
"""
if '.' in identifier:
diff --git a/babel/dates.py b/babel/dates.py
index a34f549..8b0086d 100644
--- a/babel/dates.py
+++ b/babel/dates.py
@@ -41,10 +41,10 @@ time_ = time
def get_period_names(locale=LC_TIME):
"""Return the names for day periods (AM/PM) used by the locale.
-
+
>>> get_period_names(locale='en_US')['am']
u'AM'
-
+
:param locale: the `Locale` object, or a locale string
:return: the dictionary of period names
:rtype: `dict`
@@ -53,14 +53,14 @@ def get_period_names(locale=LC_TIME):
def get_day_names(width='wide', context='format', locale=LC_TIME):
"""Return the day names used by the locale for the specified format.
-
+
>>> get_day_names('wide', locale='en_US')[1]
u'Tuesday'
>>> get_day_names('abbreviated', locale='es')[1]
u'mar'
>>> get_day_names('narrow', context='stand-alone', locale='de_DE')[1]
u'D'
-
+
:param width: the width to use, one of "wide", "abbreviated", or "narrow"
:param context: the context, either "format" or "stand-alone"
:param locale: the `Locale` object, or a locale string
@@ -71,14 +71,14 @@ def get_day_names(width='wide', context='format', locale=LC_TIME):
def get_month_names(width='wide', context='format', locale=LC_TIME):
"""Return the month names used by the locale for the specified format.
-
+
>>> get_month_names('wide', locale='en_US')[1]
u'January'
>>> get_month_names('abbreviated', locale='es')[1]
u'ene'
>>> get_month_names('narrow', context='stand-alone', locale='de_DE')[1]
u'J'
-
+
:param width: the width to use, one of "wide", "abbreviated", or "narrow"
:param context: the context, either "format" or "stand-alone"
:param locale: the `Locale` object, or a locale string
@@ -89,12 +89,12 @@ def get_month_names(width='wide', context='format', locale=LC_TIME):
def get_quarter_names(width='wide', context='format', locale=LC_TIME):
"""Return the quarter names used by the locale for the specified format.
-
+
>>> get_quarter_names('wide', locale='en_US')[1]
u'1st quarter'
>>> get_quarter_names('abbreviated', locale='de_DE')[1]
u'Q1'
-
+
:param width: the width to use, one of "wide", "abbreviated", or "narrow"
:param context: the context, either "format" or "stand-alone"
:param locale: the `Locale` object, or a locale string
@@ -105,12 +105,12 @@ def get_quarter_names(width='wide', context='format', locale=LC_TIME):
def get_era_names(width='wide', locale=LC_TIME):
"""Return the era names used by the locale for the specified format.
-
+
>>> get_era_names('wide', locale='en_US')[1]
u'Anno Domini'
>>> get_era_names('abbreviated', locale='de_DE')[1]
u'n. Chr.'
-
+
:param width: the width to use, either "wide", "abbreviated", or "narrow"
:param locale: the `Locale` object, or a locale string
:return: the dictionary of era names
@@ -121,12 +121,12 @@ def get_era_names(width='wide', locale=LC_TIME):
def get_date_format(format='medium', locale=LC_TIME):
"""Return the date formatting patterns used by the locale for the specified
format.
-
+
>>> get_date_format(locale='en_US')
<DateTimePattern u'MMM d, y'>
>>> get_date_format('full', locale='de_DE')
<DateTimePattern u'EEEE, d. MMMM y'>
-
+
:param format: the format to use, one of "full", "long", "medium", or
"short"
:param locale: the `Locale` object, or a locale string
@@ -138,10 +138,10 @@ def get_date_format(format='medium', locale=LC_TIME):
def get_datetime_format(format='medium', locale=LC_TIME):
"""Return the datetime formatting patterns used by the locale for the
specified format.
-
+
>>> get_datetime_format(locale='en_US')
u'{1}, {0}'
-
+
:param format: the format to use, one of "full", "long", "medium", or
"short"
:param locale: the `Locale` object, or a locale string
@@ -156,12 +156,12 @@ def get_datetime_format(format='medium', locale=LC_TIME):
def get_time_format(format='medium', locale=LC_TIME):
"""Return the time formatting patterns used by the locale for the specified
format.
-
+
>>> get_time_format(locale='en_US')
<DateTimePattern u'h:mm:ss a'>
>>> get_time_format('full', locale='de_DE')
<DateTimePattern u'HH:mm:ss zzzz'>
-
+
:param format: the format to use, one of "full", "long", "medium", or
"short"
:param locale: the `Locale` object, or a locale string
@@ -173,11 +173,11 @@ def get_time_format(format='medium', locale=LC_TIME):
def get_timezone_gmt(datetime=None, width='long', locale=LC_TIME):
"""Return the timezone associated with the given `datetime` object formatted
as string indicating the offset from GMT.
-
+
>>> dt = datetime(2007, 4, 1, 15, 30)
>>> get_timezone_gmt(dt, locale='en')
u'GMT+00:00'
-
+
>>> from pytz import timezone
>>> tz = timezone('America/Los_Angeles')
>>> dt = datetime(2007, 4, 1, 15, 30, tzinfo=tz)
@@ -185,13 +185,13 @@ def get_timezone_gmt(datetime=None, width='long', locale=LC_TIME):
u'GMT-08:00'
>>> get_timezone_gmt(dt, 'short', locale='en')
u'-0800'
-
+
The long format depends on the locale, for example in France the acronym
UTC string is used instead of GMT:
-
+
>>> get_timezone_gmt(dt, 'long', locale='fr_FR')
u'UTC-08:00'
-
+
:param datetime: the ``datetime`` object; if `None`, the current date and
time in UTC is used
:param width: either "long" or "short"
@@ -219,10 +219,10 @@ def get_timezone_gmt(datetime=None, width='long', locale=LC_TIME):
def get_timezone_location(dt_or_tzinfo=None, locale=LC_TIME):
"""Return a representation of the given timezone using "location format".
-
+
The result depends on both the local display name of the country and the
city associated with the time zone:
-
+
>>> from pytz import timezone
>>> tz = timezone('America/St_Johns')
>>> get_timezone_location(tz, locale='de_DE')
@@ -230,14 +230,14 @@ def get_timezone_location(dt_or_tzinfo=None, locale=LC_TIME):
>>> tz = timezone('America/Mexico_City')
>>> get_timezone_location(tz, locale='de_DE')
u'Mexiko (Mexiko-Stadt) Zeit'
-
+
If the timezone is associated with a country that uses only a single
timezone, just the localized country name is returned:
-
+
>>> tz = timezone('Europe/Berlin')
>>> get_timezone_name(tz, locale='de_DE')
u'Mitteleurop\\xe4ische Zeit'
-
+
:param dt_or_tzinfo: the ``datetime`` or ``tzinfo`` object that determines
the timezone; if `None`, the current date and time in
UTC is assumed
@@ -303,42 +303,42 @@ def get_timezone_name(dt_or_tzinfo=None, width='long', uncommon=False,
locale=LC_TIME):
r"""Return the localized display name for the given timezone. The timezone
may be specified using a ``datetime`` or `tzinfo` object.
-
+
>>> from pytz import timezone
>>> dt = time(15, 30, tzinfo=timezone('America/Los_Angeles'))
>>> get_timezone_name(dt, locale='en_US')
u'Pacific Standard Time'
>>> get_timezone_name(dt, width='short', locale='en_US')
u'PST'
-
+
If this function gets passed only a `tzinfo` object and no concrete
`datetime`, the returned display name is indenpendent of daylight savings
time. This can be used for example for selecting timezones, or to set the
time of events that recur across DST changes:
-
+
>>> tz = timezone('America/Los_Angeles')
>>> get_timezone_name(tz, locale='en_US')
u'Pacific Time'
>>> get_timezone_name(tz, 'short', locale='en_US')
u'PT'
-
+
If no localized display name for the timezone is available, and the timezone
is associated with a country that uses only a single timezone, the name of
that country is returned, formatted according to the locale:
-
+
>>> tz = timezone('Europe/Berlin')
>>> get_timezone_name(tz, locale='de_DE')
u'Mitteleurop\xe4ische Zeit'
>>> get_timezone_name(tz, locale='pt_BR')
u'Hor\xe1rio da Europa Central'
-
+
On the other hand, if the country uses multiple timezones, the city is also
included in the representation:
-
+
>>> tz = timezone('America/St_Johns')
>>> get_timezone_name(tz, locale='de_DE')
u'Neufundland-Zeit'
-
+
:param dt_or_tzinfo: the ``datetime`` or ``tzinfo`` object that determines
the timezone; if a ``tzinfo`` object is used, the
resulting display name will be generic, i.e.
@@ -411,26 +411,26 @@ def get_timezone_name(dt_or_tzinfo=None, width='long', uncommon=False,
def format_date(date=None, format='medium', locale=LC_TIME):
"""Return a date formatted according to the given pattern.
-
+
>>> d = date(2007, 04, 01)
>>> format_date(d, locale='en_US')
u'Apr 1, 2007'
>>> format_date(d, format='full', locale='de_DE')
u'Sonntag, 1. April 2007'
-
+
If you don't want to use the locale default formats, you can specify a
custom date pattern:
-
+
>>> format_date(d, "EEE, MMM d, ''yy", locale='en')
u"Sun, Apr 1, '07"
-
+
:param date: the ``date`` or ``datetime`` object; if `None`, the current
date is used
:param format: one of "full", "long", "medium", or "short", or a custom
date/time pattern
:param locale: a `Locale` object or a locale identifier
:rtype: `unicode`
-
+
:note: If the pattern contains time fields, an `AttributeError` will be
raised when trying to apply the formatting. This is also true if
the value of ``date`` parameter is actually a ``datetime`` object,
@@ -450,14 +450,14 @@ def format_date(date=None, format='medium', locale=LC_TIME):
def format_datetime(datetime=None, format='medium', tzinfo=None,
locale=LC_TIME):
r"""Return a date formatted according to the given pattern.
-
+
>>> dt = datetime(2007, 04, 01, 15, 30)
>>> format_datetime(dt, locale='en_US')
u'Apr 1, 2007, 3:30:00 PM'
-
+
For any pattern requiring the display of the time-zone, the third-party
``pytz`` package is needed to explicitly specify the time-zone:
-
+
>>> from pytz import timezone
>>> format_datetime(dt, 'full', tzinfo=timezone('Europe/Paris'),
... locale='fr_FR')
@@ -465,7 +465,7 @@ def format_datetime(datetime=None, format='medium', tzinfo=None,
>>> format_datetime(dt, "yyyy.MM.dd G 'at' HH:mm:ss zzz",
... tzinfo=timezone('US/Eastern'), locale='en')
u'2007.04.01 AD at 11:30:00 EDT'
-
+
:param datetime: the `datetime` object; if `None`, the current date and
time is used
:param format: one of "full", "long", "medium", or "short", or a custom
@@ -499,22 +499,22 @@ def format_datetime(datetime=None, format='medium', tzinfo=None,
def format_time(time=None, format='medium', tzinfo=None, locale=LC_TIME):
r"""Return a time formatted according to the given pattern.
-
+
>>> t = time(15, 30)
>>> format_time(t, locale='en_US')
u'3:30:00 PM'
>>> format_time(t, format='short', locale='de_DE')
u'15:30'
-
+
If you don't want to use the locale default formats, you can specify a
custom time pattern:
-
+
>>> format_time(t, "hh 'o''clock' a", locale='en')
u"03 o'clock PM"
-
+
For any pattern requiring the display of the time-zone, the third-party
``pytz`` package is needed to explicitly specify the time-zone:
-
+
>>> from pytz import timezone
>>> t = datetime(2007, 4, 1, 15, 30)
>>> tzinfo = timezone('Europe/Paris')
@@ -524,20 +524,20 @@ def format_time(time=None, format='medium', tzinfo=None, locale=LC_TIME):
>>> format_time(t, "hh 'o''clock' a, zzzz", tzinfo=timezone('US/Eastern'),
... locale='en')
u"09 o'clock AM, Eastern Daylight Time"
-
+
As that example shows, when this function gets passed a
``datetime.datetime`` value, the actual time in the formatted string is
adjusted to the timezone specified by the `tzinfo` parameter. If the
``datetime`` is "naive" (i.e. it has no associated timezone information),
it is assumed to be in UTC.
-
+
These timezone calculations are **not** performed if the value is of type
``datetime.time``, as without date information there's no way to determine
what a given time would translate to in a different timezone without
information about whether daylight savings time is in effect or not. This
means that time values are left as-is, and the value of the `tzinfo`
parameter is only used to display the timezone name if needed:
-
+
>>> t = time(15, 30)
>>> format_time(t, format='full', tzinfo=timezone('Europe/Paris'),
... locale='fr_FR')
@@ -545,7 +545,7 @@ def format_time(time=None, format='medium', tzinfo=None, locale=LC_TIME):
>>> format_time(t, format='full', tzinfo=timezone('US/Eastern'),
... locale='en_US')
u'3:30:00 PM Eastern Standard Time'
-
+
:param time: the ``time`` or ``datetime`` object; if `None`, the current
time in UTC is used
:param format: one of "full", "long", "medium", or "short", or a custom
@@ -553,7 +553,7 @@ def format_time(time=None, format='medium', tzinfo=None, locale=LC_TIME):
:param tzinfo: the time-zone to apply to the time for display
:param locale: a `Locale` object or a locale identifier
:rtype: `unicode`
-
+
:note: If the pattern contains date fields, an `AttributeError` will be
raised when trying to apply the formatting. This is also true if
the value of ``time`` parameter is actually a ``datetime`` object,
@@ -599,7 +599,7 @@ def format_timedelta(delta, granularity='second', threshold=.85, locale=LC_TIME)
The granularity parameter can be provided to alter the lowest unit
presented, which defaults to a second.
-
+
>>> format_timedelta(timedelta(hours=3), granularity='day',
... locale='en_US')
u'1 day'
@@ -643,15 +643,15 @@ def format_timedelta(delta, granularity='second', threshold=.85, locale=LC_TIME)
def parse_date(string, locale=LC_TIME):
"""Parse a date from a string.
-
+
This function uses the date format for the locale as a hint to determine
the order in which the date fields appear in the string.
-
+
>>> parse_date('4/1/04', locale='en_US')
datetime.date(2004, 4, 1)
>>> parse_date('01.04.2004', locale='de_DE')
datetime.date(2004, 4, 1)
-
+
:param string: the string containing the date
:param locale: a `Locale` object or a locale identifier
:return: the parsed date
@@ -686,10 +686,10 @@ def parse_date(string, locale=LC_TIME):
def parse_datetime(string, locale=LC_TIME):
"""Parse a date and time from a string.
-
+
This function uses the date and time formats for the locale as a hint to
determine the order in which the time fields appear in the string.
-
+
:param string: the string containing the date and time
:param locale: a `Locale` object or a locale identifier
:return: the parsed date/time
@@ -699,13 +699,13 @@ def parse_datetime(string, locale=LC_TIME):
def parse_time(string, locale=LC_TIME):
"""Parse a time from a string.
-
+
This function uses the time format for the locale as a hint to determine
the order in which the time fields appear in the string.
-
+
>>> parse_time('15:30:00', locale='en_US')
datetime.time(15, 30)
-
+
:param string: the string containing the time
:param locale: a `Locale` object or a locale identifier
:return: the parsed time
@@ -918,19 +918,19 @@ class DateTimeFormat(object):
def get_week_number(self, day_of_period, day_of_week=None):
"""Return the number of the week of a day within a period. This may be
the week number in a year or the week number in a month.
-
+
Usually this will return a value equal to or greater than 1, but if the
first week of the period is so short that it actually counts as the last
week of the previous period, this function will return 0.
-
+
>>> format = DateTimeFormat(date(2006, 1, 8), Locale.parse('de_DE'))
>>> format.get_week_number(6)
1
-
+
>>> format = DateTimeFormat(date(2006, 1, 8), Locale.parse('en_US'))
>>> format.get_week_number(6)
2
-
+
:param day_of_period: the number of the day in the period (usually
either the day of month or the day of year)
:param day_of_week: the week day; if ommitted, the week day of the
@@ -965,23 +965,23 @@ PATTERN_CHARS = {
def parse_pattern(pattern):
"""Parse date, time, and datetime format patterns.
-
+
>>> parse_pattern("MMMMd").format
u'%(MMMM)s%(d)s'
>>> parse_pattern("MMM d, yyyy").format
u'%(MMM)s %(d)s, %(yyyy)s'
-
+
Pattern can contain literal strings in single quotes:
-
+
>>> parse_pattern("H:mm' Uhr 'z").format
u'%(H)s:%(mm)s Uhr %(z)s'
-
+
An actual single quote can be used by using two adjacent single quote
characters:
-
+
>>> parse_pattern("hh' o''clock'").format
u"%(hh)s o'clock"
-
+
:param pattern: the formatting pattern to parse
"""
if type(pattern) is DateTimePattern:
diff --git a/babel/localedata.py b/babel/localedata.py
index d128ec8..0433a9f 100644
--- a/babel/localedata.py
+++ b/babel/localedata.py
@@ -33,7 +33,7 @@ _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`
@@ -46,7 +46,7 @@ def exists(name):
def locale_identifiers():
"""Return a list of all locale identifiers for which locale data is
available.
-
+
:return: a list of locale identifiers (strings)
:rtype: `list`
:since: version 0.8.1
@@ -58,23 +58,23 @@ def locale_identifiers():
def load(name, merge_inherited=True):
"""Load the locale data for the given locale.
-
+
The locale data is a dictionary that contains much of the data defined by
the Common Locale Data Repository (CLDR). This data is stored as a
collection of pickle files inside the ``babel`` package.
-
+
>>> d = load('en_US')
>>> d['languages']['sv']
u'Swedish'
-
+
Note that the results are cached, and subsequent requests for the same
locale return the same dictionary:
-
+
>>> d1 = load('en_US')
>>> d2 = load('en_US')
>>> d1 is d2
True
-
+
:param name: the locale identifier string (or "root")
:param merge_inherited: whether the inherited data should be merged into
the data of the requested locale
@@ -115,12 +115,12 @@ def load(name, merge_inherited=True):
def merge(dict1, dict2):
"""Merge the data from `dict2` into the `dict1` dictionary, making copies
of nested dictionaries.
-
+
>>> d = {1: 'foo', 3: 'baz'}
>>> merge(d, {1: 'Foo', 2: 'Bar'})
>>> items = d.items(); items.sort(); items
[(1, 'Foo'), (2, 'Bar'), (3, 'baz')]
-
+
:param dict1: the dictionary to merge into
:param dict2: the dictionary containing the data that should be merged
"""
@@ -147,7 +147,7 @@ def merge(dict1, dict2):
class Alias(object):
"""Representation of an alias in the locale data.
-
+
An alias is a value that refers to some other part of the locale data,
as specified by the `keys`.
"""
@@ -160,10 +160,10 @@ class Alias(object):
def resolve(self, data):
"""Resolve the alias based on the given data.
-
+
This is done recursively, so if one alias resolves to a second alias,
that second alias will also be resolved.
-
+
:param data: the locale data
:type data: `dict`
"""
diff --git a/babel/messages/catalog.py b/babel/messages/catalog.py
index d149bfb..abf96a1 100644
--- a/babel/messages/catalog.py
+++ b/babel/messages/catalog.py
@@ -686,7 +686,7 @@ class Catalog(object):
def delete(self, id, context=None):
"""Delete the message with the specified ID and context.
-
+
:param id: the message ID
:param context: the message context, or ``None`` for no context
"""
diff --git a/babel/messages/extract.py b/babel/messages/extract.py
index 60612e7..018d41b 100644
--- a/babel/messages/extract.py
+++ b/babel/messages/extract.py
@@ -263,7 +263,7 @@ def extract(method, fileobj, keywords=DEFAULT_KEYWORDS, comment_tags=(),
break
if func is None:
# if pkg_resources is not available or no usable egg-info was found
- # (see #230), we resort to looking up the builtin extractors
+ # (see #230), we resort to looking up the builtin extractors
# directly
builtin = {'ignore': extract_nothing, 'python': extract_python}
func = builtin.get(method)
diff --git a/babel/messages/frontend.py b/babel/messages/frontend.py
index c069530..350e81d 100755
--- a/babel/messages/frontend.py
+++ b/babel/messages/frontend.py
@@ -1133,7 +1133,7 @@ class CommandLineInterface(object):
try:
write_po(tmpfile, catalog,
ignore_obsolete=options.ignore_obsolete,
- include_previous=options.previous,
+ include_previous=options.previous,
width=options.width)
finally:
tmpfile.close()
@@ -1163,7 +1163,7 @@ def parse_mapping(fileobj, filename=None):
>>> buf = StringIO('''
... [extractors]
... custom = mypackage.module:myfunc
- ...
+ ...
... # Python source files
... [python: **.py]
...
@@ -1173,7 +1173,7 @@ def parse_mapping(fileobj, filename=None):
... [genshi: **/templates/**.txt]
... template_class = genshi.template:TextTemplate
... encoding = latin-1
- ...
+ ...
... # Some custom extractor
... [custom: **/custom/*.*]
... ''')
diff --git a/babel/messages/mofile.py b/babel/messages/mofile.py
index e7d1a39..4a21eff 100644
--- a/babel/messages/mofile.py
+++ b/babel/messages/mofile.py
@@ -33,11 +33,11 @@ BE_MAGIC = 0xde120495L
def read_mo(fileobj):
"""Read a binary MO file from the given file-like object and return a
corresponding `Catalog` object.
-
+
:param fileobj: the file-like object to read the MO file from
:return: a catalog object representing the parsed MO file
:rtype: `Catalog`
-
+
:note: The implementation of this function is heavily based on the
``GNUTranslations._parse`` method of the ``gettext`` module in the
standard library.
@@ -118,11 +118,11 @@ def read_mo(fileobj):
def write_mo(fileobj, catalog, use_fuzzy=False):
"""Write a catalog to the specified file-like object using the GNU MO file
format.
-
+
>>> from babel.messages import Catalog
>>> from gettext import GNUTranslations
>>> from StringIO import StringIO
-
+
>>> catalog = Catalog(locale='en_US')
>>> catalog.add('foo', 'Voh')
<Message ...>
@@ -135,7 +135,7 @@ def write_mo(fileobj, catalog, use_fuzzy=False):
>>> catalog.add(('Fuzz', 'Fuzzes'), ('', ''))
<Message ...>
>>> buf = StringIO()
-
+
>>> write_mo(buf, catalog)
>>> buf.seek(0)
>>> translations = GNUTranslations(fp=buf)
@@ -153,7 +153,7 @@ def write_mo(fileobj, catalog, use_fuzzy=False):
u'Fuzz'
>>> translations.ugettext('Fuzzes')
u'Fuzzes'
-
+
:param fileobj: the file-like object to write to
:param catalog: the `Catalog` instance
:param use_fuzzy: whether translations marked as "fuzzy" should be included
diff --git a/babel/messages/tests/catalog.py b/babel/messages/tests/catalog.py
index 64d112b..6bf96e4 100644
--- a/babel/messages/tests/catalog.py
+++ b/babel/messages/tests/catalog.py
@@ -245,7 +245,7 @@ class CatalogTestCase(unittest.TestCase):
self.assertEqual(None, cat2['foo'].string)
self.assertEqual(False, cat2['foo'].fuzzy)
-
+
def test_update_po_updates_pot_creation_date(self):
template = catalog.Catalog()
localized_catalog = copy.deepcopy(template)
@@ -259,7 +259,7 @@ class CatalogTestCase(unittest.TestCase):
localized_catalog.update(template)
self.assertEqual(template.creation_date,
localized_catalog.creation_date)
-
+
def test_update_po_keeps_po_revision_date(self):
template = catalog.Catalog()
localized_catalog = copy.deepcopy(template)
@@ -278,30 +278,30 @@ class CatalogTestCase(unittest.TestCase):
def test_stores_datetime_correctly(self):
localized = catalog.Catalog()
localized.locale = 'de_DE'
- localized[''] = catalog.Message('',
+ localized[''] = catalog.Message('',
"POT-Creation-Date: 2009-03-09 15:47-0700\n" +
"PO-Revision-Date: 2009-03-09 15:47-0700\n")
for key, value in localized.mime_headers:
if key in ('POT-Creation-Date', 'PO-Revision-Date'):
self.assertEqual(value, '2009-03-09 15:47-0700')
-
+
def test_mime_headers_contain_same_information_as_attributes(self):
cat = catalog.Catalog()
- cat[''] = catalog.Message('',
+ cat[''] = catalog.Message('',
"Last-Translator: Foo Bar <foo.bar@example.com>\n" +
"Language-Team: de <de@example.com>\n" +
"POT-Creation-Date: 2009-03-01 11:20+0200\n" +
"PO-Revision-Date: 2009-03-09 15:47-0700\n")
self.assertEqual(None, cat.locale)
mime_headers = dict(cat.mime_headers)
-
+
self.assertEqual('Foo Bar <foo.bar@example.com>', cat.last_translator)
- self.assertEqual('Foo Bar <foo.bar@example.com>',
+ self.assertEqual('Foo Bar <foo.bar@example.com>',
mime_headers['Last-Translator'])
-
+
self.assertEqual('de <de@example.com>', cat.language_team)
self.assertEqual('de <de@example.com>', mime_headers['Language-Team'])
-
+
dt = datetime.datetime(2009, 3, 9, 15, 47, tzinfo=FixedOffsetTimezone(-7 * 60))
self.assertEqual(dt, cat.revision_date)
formatted_dt = format_datetime(dt, 'yyyy-MM-dd HH:mmZ', locale='en')
diff --git a/babel/messages/tests/frontend.py b/babel/messages/tests/frontend.py
index c5b8ba1..2a9349a 100644
--- a/babel/messages/tests/frontend.py
+++ b/babel/messages/tests/frontend.py
@@ -114,7 +114,7 @@ class ExtractMessagesTestCase(unittest.TestCase):
self.cmd.output_file = self._pot_file()
self.cmd.finalize_options()
self.cmd.run()
-
+
catalog = read_po(open(self._pot_file(), 'U'))
msg = catalog.get('bar')
self.assertEqual(1, len(msg.locations))
@@ -124,7 +124,7 @@ class ExtractMessagesTestCase(unittest.TestCase):
self.cmd.input_dirs = 'foo, bar'
self.cmd.output_file = self._pot_file()
self.cmd.finalize_options()
-
+
self.assertEqual(['foo', 'bar'], self.cmd.input_dirs)
def test_extraction_with_default_mapping(self):
@@ -319,7 +319,7 @@ class InitCatalogTestCase(unittest.TestCase):
return os.path.join(self.datadir, 'project', 'i18n')
def _po_file(self, locale):
- return os.path.join(self._i18n_dir(), locale, 'LC_MESSAGES',
+ return os.path.join(self._i18n_dir(), locale, 'LC_MESSAGES',
'messages.po')
def test_no_input_file(self):
@@ -528,14 +528,14 @@ msgstr[0] ""
'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ',
tzinfo=LOCALTZ, locale='ja_JP')},
open(po_file, 'U').read())
-
+
def test_supports_no_wrap(self):
self.cmd.input_file = 'project/i18n/long_messages.pot'
self.cmd.locale = 'en_US'
self.cmd.output_dir = 'project/i18n'
-
+
long_message = '"'+ 'xxxxx '*15 + '"'
-
+
pot_contents = open('project/i18n/messages.pot', 'U').read()
pot_with_very_long_line = pot_contents.replace('"bar"', long_message)
open(self.cmd.input_file, 'wb').write(pot_with_very_long_line)
@@ -552,7 +552,7 @@ r"""# English (United States) translations for TestProject.
# This file is distributed under the same license as the TestProject
# project.
# FIRST AUTHOR <EMAIL@ADDRESS>, 2007.
-#
+#
msgid ""
msgstr ""
"Project-Id-Version: TestProject 0.1\n"
@@ -584,14 +584,14 @@ msgstr[1] ""
tzinfo=LOCALTZ, locale='en_US'),
'long_message': long_message},
open(po_file, 'U').read())
-
+
def test_supports_width(self):
self.cmd.input_file = 'project/i18n/long_messages.pot'
self.cmd.locale = 'en_US'
self.cmd.output_dir = 'project/i18n'
-
+
long_message = '"'+ 'xxxxx '*15 + '"'
-
+
pot_contents = open('project/i18n/messages.pot', 'U').read()
pot_with_very_long_line = pot_contents.replace('"bar"', long_message)
open(self.cmd.input_file, 'wb').write(pot_with_very_long_line)
@@ -653,7 +653,7 @@ class CommandLineInterfaceTestCase(unittest.TestCase):
sys.stdout = StringIO()
sys.stderr = StringIO()
os.chdir(self.datadir)
-
+
self._remove_log_handlers()
self.cli = frontend.CommandLineInterface()
@@ -662,15 +662,15 @@ class CommandLineInterfaceTestCase(unittest.TestCase):
sys.argv = self.orig_argv
sys.stdout = self.orig_stdout
sys.stderr = self.orig_stderr
- for dirname in ['lv_LV', 'ja_JP']:
+ for dirname in ['lv_LV', 'ja_JP']:
locale_dir = os.path.join(self._i18n_dir(), dirname)
if os.path.isdir(locale_dir):
shutil.rmtree(locale_dir)
self._remove_log_handlers()
def _remove_log_handlers(self):
- # Logging handlers will be reused if possible (#227). This breaks the
- # implicit assumption that our newly created StringIO for sys.stderr
+ # Logging handlers will be reused if possible (#227). This breaks the
+ # implicit assumption that our newly created StringIO for sys.stderr
# contains the console output. Removing the old handler ensures that a
# new handler with our new StringIO instance will be used.
log = logging.getLogger('babel')
@@ -701,8 +701,8 @@ pybabel: error: no valid command or option passed. try the -h/--help option for
first_output = sys.stderr.getvalue()
self._run_init_catalog()
second_output = sys.stderr.getvalue()[len(first_output):]
-
- # in case the log message is not duplicated we should get the same
+
+ # in case the log message is not duplicated we should get the same
# output as before
self.assertEqual(first_output, second_output)
@@ -710,7 +710,7 @@ pybabel: error: no valid command or option passed. try the -h/--help option for
custom_stream = StringIO()
log = logging.getLogger('babel')
log.addHandler(logging.StreamHandler(custom_stream))
-
+
self._run_init_catalog()
self.assertNotEqual(id(sys.stderr), id(custom_stream))
self.assertEqual('', sys.stderr.getvalue())
@@ -941,7 +941,7 @@ msgstr[0] ""
'date': format_datetime(datetime.now(LOCALTZ), 'yyyy-MM-dd HH:mmZ',
tzinfo=LOCALTZ, locale='en')},
open(po_file, 'U').read())
-
+
def test_init_more_than_2_plural_forms(self):
po_file = self._po_file('lv_LV')
self.cli.run(sys.argv + ['init',
@@ -1017,7 +1017,7 @@ compiling catalog %r to %r
os.unlink(mo_file)
def _po_file(self, locale):
- return os.path.join(self._i18n_dir(), locale, 'LC_MESSAGES',
+ return os.path.join(self._i18n_dir(), locale, 'LC_MESSAGES',
'messages.po')
def test_compile_catalog_with_more_than_2_plural_forms(self):
diff --git a/babel/messages/tests/pofile.py b/babel/messages/tests/pofile.py
index 7e5904f..9d1d437 100644
--- a/babel/messages/tests/pofile.py
+++ b/babel/messages/tests/pofile.py
@@ -206,7 +206,7 @@ msgstr "Bahr"
self.assertEqual('Menu', message.context)
message = catalog.get('bar', context='Mannu')
self.assertEqual('Mannu', message.context)
-
+
# And verify it pass through write_po
out_buf = StringIO()
pofile.write_po(out_buf, catalog, omit_header=True)
@@ -290,7 +290,7 @@ msgid "foo"
msgstr ""''', buf.getvalue().strip())
def test_wrap_long_lines(self):
- text = """Here's some text where
+ text = """Here's some text where
white space and line breaks matter, and should
not be removed
@@ -325,7 +325,7 @@ includesareallylongwordthatmightbutshouldnt throw us into an infinite loop
" throw us into an infinite "
"loop\n"
msgstr ""''', buf.getvalue().strip())
-
+
def test_wrap_long_lines_in_header(self):
"""
Verify that long lines in the header comment are wrapped correctly.
@@ -357,7 +357,7 @@ msgstr ""''', buf.getvalue().strip())
#: doupy/templates/job-offers/helpers.html:22
msgid "foo"
msgstr ""''', buf.getvalue().strip())
-
+
def test_no_wrap_and_width_behaviour_on_comments(self):
catalog = Catalog()
catalog.add("Pretty dam long message id, which must really be big "
@@ -539,15 +539,15 @@ class PofileFunctionsTestCase(unittest.TestCase):
def test_unescape_of_quoted_newline(self):
# regression test for #198
self.assertEqual(r'\n', pofile.unescape(r'"\\n"'))
-
+
def test_denormalize_on_msgstr_without_empty_first_line(self):
- # handle irregular multi-line msgstr (no "" as first line)
+ # handle irregular multi-line msgstr (no "" as first line)
# gracefully (#171)
msgstr = '"multi-line\\n"\n" translation"'
expected_denormalized = u'multi-line\n translation'
-
+
self.assertEqual(expected_denormalized, pofile.denormalize(msgstr))
- self.assertEqual(expected_denormalized,
+ self.assertEqual(expected_denormalized,
pofile.denormalize('""\n' + msgstr))
diff --git a/babel/numbers.py b/babel/numbers.py
index 9728cc9..4ee9a70 100644
--- a/babel/numbers.py
+++ b/babel/numbers.py
@@ -38,10 +38,10 @@ LC_NUMERIC = default_locale('LC_NUMERIC')
def get_currency_name(currency, locale=LC_NUMERIC):
"""Return the name used by the locale for the specified currency.
-
+
>>> get_currency_name('USD', 'en_US')
u'US Dollar'
-
+
:param currency: the currency code
:param locale: the `Locale` object or locale identifier
:return: the currency symbol
@@ -52,10 +52,10 @@ def get_currency_name(currency, locale=LC_NUMERIC):
def get_currency_symbol(currency, locale=LC_NUMERIC):
"""Return the symbol used by the locale for the specified currency.
-
+
>>> get_currency_symbol('USD', 'en_US')
u'$'
-
+
:param currency: the currency code
:param locale: the `Locale` object or locale identifier
:return: the currency symbol
@@ -65,10 +65,10 @@ def get_currency_symbol(currency, locale=LC_NUMERIC):
def get_decimal_symbol(locale=LC_NUMERIC):
"""Return the symbol used by the locale to separate decimal fractions.
-
+
>>> get_decimal_symbol('en_US')
u'.'
-
+
:param locale: the `Locale` object or locale identifier
:return: the decimal symbol
:rtype: `unicode`
@@ -77,10 +77,10 @@ def get_decimal_symbol(locale=LC_NUMERIC):
def get_plus_sign_symbol(locale=LC_NUMERIC):
"""Return the plus sign symbol used by the current locale.
-
+
>>> get_plus_sign_symbol('en_US')
u'+'
-
+
:param locale: the `Locale` object or locale identifier
:return: the plus sign symbol
:rtype: `unicode`
@@ -89,10 +89,10 @@ def get_plus_sign_symbol(locale=LC_NUMERIC):
def get_minus_sign_symbol(locale=LC_NUMERIC):
"""Return the plus sign symbol used by the current locale.
-
+
>>> get_minus_sign_symbol('en_US')
u'-'
-
+
:param locale: the `Locale` object or locale identifier
:return: the plus sign symbol
:rtype: `unicode`
@@ -101,10 +101,10 @@ def get_minus_sign_symbol(locale=LC_NUMERIC):
def get_exponential_symbol(locale=LC_NUMERIC):
"""Return the symbol used by the locale to separate mantissa and exponent.
-
+
>>> get_exponential_symbol('en_US')
u'E'
-
+
:param locale: the `Locale` object or locale identifier
:return: the exponential symbol
:rtype: `unicode`
@@ -113,10 +113,10 @@ def get_exponential_symbol(locale=LC_NUMERIC):
def get_group_symbol(locale=LC_NUMERIC):
"""Return the symbol used by the locale to separate groups of thousands.
-
+
>>> get_group_symbol('en_US')
u','
-
+
:param locale: the `Locale` object or locale identifier
:return: the group symbol
:rtype: `unicode`
@@ -125,13 +125,13 @@ def get_group_symbol(locale=LC_NUMERIC):
def format_number(number, locale=LC_NUMERIC):
u"""Return the given number formatted for a specific locale.
-
+
>>> format_number(1099, locale='en_US')
u'1,099'
>>> format_number(1099, locale='de_DE')
u'1.099'
-
+
:param number: the number to format
:param locale: the `Locale` object or locale identifier
:return: the formatted number
@@ -142,7 +142,7 @@ def format_number(number, locale=LC_NUMERIC):
def format_decimal(number, format=None, locale=LC_NUMERIC):
u"""Return the given decimal number formatted for a specific locale.
-
+
>>> format_decimal(1.2345, locale='en_US')
u'1.234'
>>> format_decimal(1.2346, locale='en_US')
@@ -156,12 +156,12 @@ def format_decimal(number, format=None, locale=LC_NUMERIC):
The appropriate thousands grouping and the decimal separator are used for
each locale:
-
+
>>> format_decimal(12345.5, locale='en_US')
u'12,345.5'
:param number: the number to format
- :param format:
+ :param format:
:param locale: the `Locale` object or locale identifier
:return: the formatted decimal number
:rtype: `unicode`
@@ -174,19 +174,19 @@ def format_decimal(number, format=None, locale=LC_NUMERIC):
def format_currency(number, currency, format=None, locale=LC_NUMERIC):
u"""Return formatted currency value.
-
+
>>> format_currency(1099.98, 'USD', locale='en_US')
u'$1,099.98'
>>> format_currency(1099.98, 'USD', locale='es_CO')
u'1.099,98\\xa0US$'
>>> format_currency(1099.98, 'EUR', locale='de_DE')
u'1.099,98\\xa0\\u20ac'
-
+
The pattern can also be specified explicitly:
-
+
>>> format_currency(1099.98, 'EUR', u'\xa4\xa4 #,##0.00', locale='en_US')
u'EUR 1,099.98'
-
+
:param number: the number to format
:param currency: the currency code
:param locale: the `Locale` object or locale identifier
@@ -201,7 +201,7 @@ def format_currency(number, currency, format=None, locale=LC_NUMERIC):
def format_percent(number, format=None, locale=LC_NUMERIC):
"""Return formatted percent value for a specific locale.
-
+
>>> format_percent(0.34, locale='en_US')
u'34%'
>>> format_percent(25.1234, locale='en_US')
@@ -210,12 +210,12 @@ def format_percent(number, format=None, locale=LC_NUMERIC):
u'2\\xa0512\\xa0%'
The format pattern can also be specified explicitly:
-
+
>>> format_percent(25.1234, u'#,##0\u2030', locale='en_US')
u'25,123\u2030'
:param number: the percent number to format
- :param format:
+ :param format:
:param locale: the `Locale` object or locale identifier
:return: the formatted percent number
:rtype: `unicode`
@@ -228,17 +228,17 @@ def format_percent(number, format=None, locale=LC_NUMERIC):
def format_scientific(number, format=None, locale=LC_NUMERIC):
"""Return value formatted in scientific notation for a specific locale.
-
+
>>> format_scientific(10000, locale='en_US')
u'1E4'
The format pattern can also be specified explicitly:
-
+
>>> format_scientific(1234567, u'##0E00', locale='en_US')
u'1.23E06'
:param number: the number to format
- :param format:
+ :param format:
:param locale: the `Locale` object or locale identifier
:return: value formatted in scientific notation.
:rtype: `unicode`
@@ -256,19 +256,19 @@ class NumberFormatError(ValueError):
def parse_number(string, locale=LC_NUMERIC):
"""Parse localized number string into a long integer.
-
+
>>> parse_number('1,099', locale='en_US')
1099L
>>> parse_number('1.099', locale='de_DE')
1099L
-
+
When the given string cannot be parsed, an exception is raised:
-
+
>>> parse_number('1.099,98', locale='de')
Traceback (most recent call last):
...
NumberFormatError: '1.099,98' is not a valid number
-
+
:param string: the string to parse
:param locale: the `Locale` object or locale identifier
:return: the parsed number
@@ -282,19 +282,19 @@ def parse_number(string, locale=LC_NUMERIC):
def parse_decimal(string, locale=LC_NUMERIC):
"""Parse localized decimal string into a decimal.
-
+
>>> parse_decimal('1,099.98', locale='en_US')
Decimal('1099.98')
>>> parse_decimal('1.099,98', locale='de')
Decimal('1099.98')
-
+
When the given string cannot be parsed, an exception is raised:
-
+
>>> parse_decimal('2,109,998', locale='de')
Traceback (most recent call last):
...
NumberFormatError: '2,109,998' is not a valid decimal number
-
+
:param string: the string to parse
:param locale: the `Locale` object or locale identifier
:return: the parsed decimal number
@@ -325,15 +325,15 @@ def split_number(value):
if isinstance(value, Decimal):
# NB can't just do text = str(value) as str repr of Decimal may be
# in scientific notation, e.g. for small numbers.
-
+
sign, digits, exp = value.as_tuple()
# build list of digits in reverse order, then reverse+join
# as per http://docs.python.org/library/decimal.html#recipes
int_part = []
frac_part = []
-
+
digits = map(str, digits)
-
+
# get figures after decimal point
for i in range(-exp):
# add digit if available, else 0
@@ -341,22 +341,22 @@ def split_number(value):
frac_part.append(digits.pop())
else:
frac_part.append('0')
-
+
# add in some zeroes...
for i in range(exp):
int_part.append('0')
-
+
# and the rest
while digits:
int_part.append(digits.pop())
-
+
# if < 1, int_part must be set to '0'
if len(int_part) == 0:
int_part = '0',
-
+
if sign:
int_part.append('-')
-
+
return ''.join(reversed(int_part)), ''.join(reversed(frac_part))
text = ('%.9f' % value).rstrip('0')
if '.' in text:
@@ -482,9 +482,9 @@ def parse_pattern(pattern):
exp_plus = None
exp_prec = None
grouping = parse_grouping(integer)
- return NumberPattern(pattern, (pos_prefix, neg_prefix),
+ return NumberPattern(pattern, (pos_prefix, neg_prefix),
(pos_suffix, neg_suffix), grouping,
- int_prec, frac_prec,
+ int_prec, frac_prec,
exp_prec, exp_plus)
@@ -540,8 +540,8 @@ class NumberPattern(object):
exp_sign = get_plus_sign_symbol(locale)
exp = abs(exp)
number = u'%s%s%s%s' % \
- (self._format_sigdig(value, self.frac_prec[0],
- self.frac_prec[1]),
+ (self._format_sigdig(value, self.frac_prec[0],
+ self.frac_prec[1]),
get_exponential_symbol(locale), exp_sign,
self._format_int(str(exp), self.exp_prec[0],
self.exp_prec[1], locale))
@@ -558,7 +558,7 @@ class NumberPattern(object):
else:
number = self._format_int(text, 0, 1000, locale)
else: # A normal number pattern
- a, b = split_number(bankersround(abs(value),
+ a, b = split_number(bankersround(abs(value),
self.frac_prec[1]))
b = b or '0'
a = self._format_int(a, self.int_prec[0],
diff --git a/babel/plural.py b/babel/plural.py
index 378d81f..e298219 100644
--- a/babel/plural.py
+++ b/babel/plural.py
@@ -89,7 +89,7 @@ class PluralRule(object):
@property
def rules(self):
"""The `PluralRule` as a dict of unicode plural rules.
-
+
>>> rule = PluralRule({'one': 'n is 1'})
>>> rule.rules
{'one': 'n is 1'}
diff --git a/babel/support.py b/babel/support.py
index f6e6643..cde1448 100644
--- a/babel/support.py
+++ b/babel/support.py
@@ -35,7 +35,7 @@ __docformat__ = 'restructuredtext en'
class Format(object):
"""Wrapper class providing the various date and number formatting functions
bound to a specific locale and time-zone.
-
+
>>> fmt = Format('en_US', UTC)
>>> fmt.date(date(2007, 4, 1))
u'Apr 1, 2007'
@@ -45,7 +45,7 @@ class Format(object):
def __init__(self, locale, tzinfo=None):
"""Initialize the formatter.
-
+
:param locale: the locale identifier or `Locale` instance
:param tzinfo: the time-zone info (a `tzinfo` instance or `None`)
"""
@@ -54,23 +54,23 @@ class Format(object):
def date(self, date=None, format='medium'):
"""Return a date formatted according to the given pattern.
-
+
>>> fmt = Format('en_US')
>>> fmt.date(date(2007, 4, 1))
u'Apr 1, 2007'
-
+
:see: `babel.dates.format_date`
"""
return format_date(date, format, locale=self.locale)
def datetime(self, datetime=None, format='medium'):
"""Return a date and time formatted according to the given pattern.
-
+
>>> from pytz import timezone
>>> fmt = Format('en_US', tzinfo=timezone('US/Eastern'))
>>> fmt.datetime(datetime(2007, 4, 1, 15, 30))
u'Apr 1, 2007, 11:30:00 AM'
-
+
:see: `babel.dates.format_datetime`
"""
return format_datetime(datetime, format, tzinfo=self.tzinfo,
@@ -78,23 +78,23 @@ class Format(object):
def time(self, time=None, format='medium'):
"""Return a time formatted according to the given pattern.
-
+
>>> from pytz import timezone
>>> fmt = Format('en_US', tzinfo=timezone('US/Eastern'))
>>> fmt.time(datetime(2007, 4, 1, 15, 30))
u'11:30:00 AM'
-
+
:see: `babel.dates.format_time`
"""
return format_time(time, format, tzinfo=self.tzinfo, locale=self.locale)
def timedelta(self, delta, granularity='second', threshold=.85):
"""Return a time delta according to the rules of the given locale.
-
+
>>> fmt = Format('en_US')
>>> fmt.timedelta(timedelta(weeks=11))
u'3 mths'
-
+
:see: `babel.dates.format_timedelta`
"""
return format_timedelta(delta, granularity=granularity,
@@ -102,47 +102,47 @@ class Format(object):
def number(self, number):
"""Return an integer number formatted for the locale.
-
+
>>> fmt = Format('en_US')
>>> fmt.number(1099)
u'1,099'
-
+
:see: `babel.numbers.format_number`
"""
return format_number(number, locale=self.locale)
def decimal(self, number, format=None):
"""Return a decimal number formatted for the locale.
-
+
>>> fmt = Format('en_US')
>>> fmt.decimal(1.2345)
u'1.234'
-
+
:see: `babel.numbers.format_decimal`
"""
return format_decimal(number, format, locale=self.locale)
def currency(self, number, currency):
"""Return a number in the given currency formatted for the locale.
-
+
:see: `babel.numbers.format_currency`
"""
return format_currency(number, currency, locale=self.locale)
def percent(self, number, format=None):
"""Return a number formatted as percentage for the locale.
-
+
>>> fmt = Format('en_US')
>>> fmt.percent(0.34)
u'34%'
-
+
:see: `babel.numbers.format_percent`
"""
return format_percent(number, format, locale=self.locale)
def scientific(self, number):
"""Return a number formatted using scientific notation for the locale.
-
+
:see: `babel.numbers.format_scientific`
"""
return format_scientific(number, locale=self.locale)
@@ -151,7 +151,7 @@ class Format(object):
class LazyProxy(object):
"""Class for proxy objects that delegate to a specified function to evaluate
the actual object.
-
+
>>> def greeting(name='world'):
... return 'Hello, %s!' % name
>>> lazy_greeting = LazyProxy(greeting, name='Joe')
@@ -161,16 +161,16 @@ class LazyProxy(object):
u' Hello, Joe!'
>>> u'(%s)' % lazy_greeting
u'(Hello, Joe!)'
-
+
This can be used, for example, to implement lazy translation functions that
delay the actual translation until the string is actually used. The
rationale for such behavior is that the locale of the user may not always
be available. In web applications, you only know the locale when processing
a request.
-
+
The proxy implementation attempts to be as complete as possible, so that
the lazy objects should mostly work as expected, for example for sorting:
-
+
>>> greetings = [
... LazyProxy(greeting, 'world'),
... LazyProxy(greeting, 'Joe'),
@@ -282,7 +282,7 @@ class LazyProxy(object):
self.value[key] = value
-class NullTranslations(gettext.NullTranslations, object):
+class NullTranslations(gettext.NullTranslations, object):
DEFAULT_DOMAIN = None
@@ -308,13 +308,13 @@ class NullTranslations(gettext.NullTranslations, object):
domain.
"""
return self._domains.get(domain, self).gettext(message)
-
+
def ldgettext(self, domain, message):
- """Like ``lgettext()``, but look the message up in the specified
+ """Like ``lgettext()``, but look the message up in the specified
domain.
- """
+ """
return self._domains.get(domain, self).lgettext(message)
-
+
def udgettext(self, domain, message):
"""Like ``ugettext()``, but look the message up in the specified
domain.
@@ -322,19 +322,19 @@ class NullTranslations(gettext.NullTranslations, object):
return self._domains.get(domain, self).ugettext(message)
# backward compatibility with 0.9
dugettext = udgettext
-
+
def dngettext(self, domain, singular, plural, num):
"""Like ``ngettext()``, but look the message up in the specified
domain.
"""
return self._domains.get(domain, self).ngettext(singular, plural, num)
-
+
def ldngettext(self, domain, singular, plural, num):
"""Like ``lngettext()``, but look the message up in the specified
domain.
"""
return self._domains.get(domain, self).lngettext(singular, plural, num)
-
+
def udngettext(self, domain, singular, plural, num):
"""Like ``ungettext()`` but look the message up in the specified
domain.
@@ -345,7 +345,7 @@ class NullTranslations(gettext.NullTranslations, object):
# Most of the downwards code, until it get's included in stdlib, from:
# http://bugs.python.org/file10036/gettext-pgettext.patch
- #
+ #
# The encoding of a msgctxt and a msgid in a .mo file is
# msgctxt + "\x04" + msgid (gettext version >= 0.15)
CONTEXT_ENCODING = '%s\x04%s'
@@ -393,7 +393,7 @@ class NullTranslations(gettext.NullTranslations, object):
message id for purposes of lookup in the catalog, while `num` is used to
determine which plural form to use. The returned message string is an
8-bit string encoded with the catalog's charset encoding, if known.
-
+
If the message id for `context` is not found in the catalog, and a
fallback is specified, the request is forwarded to the fallback's
``npgettext()`` method. Otherwise, when ``num`` is 1 ``singular`` is
@@ -455,7 +455,7 @@ class NullTranslations(gettext.NullTranslations, object):
message id for purposes of lookup in the catalog, while `num` is used to
determine which plural form to use. The returned message string is a
Unicode string.
-
+
If the message id for `context` is not found in the catalog, and a
fallback is specified, the request is forwarded to the fallback's
``unpgettext()`` method. Otherwise, when `num` is 1 `singular` is
@@ -478,7 +478,7 @@ class NullTranslations(gettext.NullTranslations, object):
`domain`.
"""
return self._domains.get(domain, self).pgettext(context, message)
-
+
def udpgettext(self, domain, context, message):
"""Like `upgettext()`, but look the message up in the specified
`domain`.
@@ -500,7 +500,7 @@ class NullTranslations(gettext.NullTranslations, object):
"""
return self._domains.get(domain, self).npgettext(context, singular,
plural, num)
-
+
def udnpgettext(self, domain, context, singular, plural, num):
"""Like ``unpgettext``, but look the message up in the specified
`domain`.
diff --git a/babel/tests/core.py b/babel/tests/core.py
index 894387b..95395b5 100644
--- a/babel/tests/core.py
+++ b/babel/tests/core.py
@@ -20,19 +20,19 @@ from babel.core import default_locale, Locale
class LocaleEnvironmentTestMixin(object):
-
+
def setUp(self):
self._old_locale_settings = self.current_locale_settings()
-
+
def tearDown(self):
self.reset_locale_settings(self._old_locale_settings)
-
+
def current_locale_settings(self):
settings = {}
for name in ('LC_MESSAGES', 'LANGUAGE', 'LC_ALL', 'LC_CTYPE', 'LANG'):
settings[name] = os.environ.get(name)
return settings
-
+
def reset_locale_settings(self, settings):
for name, value in settings.items():
if value is not None:
@@ -42,33 +42,33 @@ class LocaleEnvironmentTestMixin(object):
class LocaleTest(LocaleEnvironmentTestMixin, unittest.TestCase):
-
+
def test_locale_provides_access_to_cldr_locale_data(self):
locale = Locale('en', 'US')
self.assertEqual(u'English (United States)', locale.display_name)
self.assertEqual(u'.', locale.number_symbols['decimal'])
-
+
def test_repr(self):
- self.assertEqual("Locale('de', territory='DE')",
+ self.assertEqual("Locale('de', territory='DE')",
repr(Locale('de', 'DE')))
- self.assertEqual("Locale('zh', territory='CN', script='Hans')",
+ self.assertEqual("Locale('zh', territory='CN', script='Hans')",
repr(Locale('zh', 'CN', script='Hans')))
def test_locale_comparison(self):
en_US = Locale('en', 'US')
self.assertEqual(en_US, en_US)
self.assertNotEqual(None, en_US)
-
+
bad_en_US = Locale('en_US')
self.assertNotEqual(en_US, bad_en_US)
-
+
def test_can_return_default_locale(self):
os.environ['LC_MESSAGES'] = 'fr_FR.UTF-8'
self.assertEqual(Locale('fr', 'FR'), Locale.default('LC_MESSAGES'))
-
+
class DefaultLocaleTest(LocaleEnvironmentTestMixin, unittest.TestCase):
-
+
def test_ignore_invalid_locales_in_lc_ctype(self):
# This is a regression test specifically for a bad LC_CTYPE setting on
# MacOS X 10.6 (#200)
diff --git a/babel/tests/dates.py b/babel/tests/dates.py
index e5da1b1..ece32aa 100644
--- a/babel/tests/dates.py
+++ b/babel/tests/dates.py
@@ -91,7 +91,7 @@ class DateTimeFormatTestCase(unittest.TestCase):
d = date(2007, 4, 1)
fmt = dates.DateTimeFormat(d, locale='en_US')
self.assertEqual('91', fmt['D'])
-
+
def test_day_of_year_works_with_datetime(self):
d = datetime(2007, 4, 1)
fmt = dates.DateTimeFormat(d, locale='en_US')
@@ -265,7 +265,7 @@ class FormatTimeTestCase(unittest.TestCase):
epoch = float(calendar.timegm(d.timetuple()))
formatted_time = dates.format_time(epoch, format='long', locale='en_US')
self.assertEqual(u'3:30:29 PM +0000', formatted_time)
-
+
def test_with_date_fields_in_pattern(self):
self.assertRaises(AttributeError, dates.format_time, date(2007, 04, 01),
diff --git a/babel/tests/numbers.py b/babel/tests/numbers.py
index 3e560de..1d1f795 100644
--- a/babel/tests/numbers.py
+++ b/babel/tests/numbers.py
@@ -22,30 +22,30 @@ from babel import numbers
class FormatDecimalTestCase(unittest.TestCase):
def test_patterns(self):
- self.assertEqual(numbers.format_decimal(12345, '##0',
+ self.assertEqual(numbers.format_decimal(12345, '##0',
locale='en_US'), '12345')
- self.assertEqual(numbers.format_decimal(6.5, '0.00', locale='sv'),
+ self.assertEqual(numbers.format_decimal(6.5, '0.00', locale='sv'),
'6,50')
- self.assertEqual(numbers.format_decimal(10.0**20,
- '#.00', locale='en_US'),
+ self.assertEqual(numbers.format_decimal(10.0**20,
+ '#.00', locale='en_US'),
'100000000000000000000.00')
# regression test for #183, fraction digits were not correctly cutted
- # if the input was a float value and the value had more than 7
+ # if the input was a float value and the value had more than 7
# significant digits
self.assertEqual(u'12,345,678.05',
- numbers.format_decimal(12345678.051, '#,##0.00',
+ numbers.format_decimal(12345678.051, '#,##0.00',
locale='en_US'))
def test_subpatterns(self):
- self.assertEqual(numbers.format_decimal(-12345, '#,##0.##;-#',
+ self.assertEqual(numbers.format_decimal(-12345, '#,##0.##;-#',
locale='en_US'), '-12,345')
- self.assertEqual(numbers.format_decimal(-12345, '#,##0.##;(#)',
+ self.assertEqual(numbers.format_decimal(-12345, '#,##0.##;(#)',
locale='en_US'), '(12,345)')
def test_default_rounding(self):
"""
Testing Round-Half-Even (Banker's rounding)
-
+
A '5' is rounded to the closest 'even' number
"""
self.assertEqual(numbers.format_decimal(5.5, '0', locale='sv'), '6')
@@ -56,54 +56,54 @@ class FormatDecimalTestCase(unittest.TestCase):
def test_significant_digits(self):
"""Test significant digits patterns"""
- self.assertEqual(numbers.format_decimal(123004, '@@',locale='en_US'),
+ self.assertEqual(numbers.format_decimal(123004, '@@',locale='en_US'),
'120000')
self.assertEqual(numbers.format_decimal(1.12, '@', locale='sv'), '1')
self.assertEqual(numbers.format_decimal(1.1, '@@', locale='sv'), '1,1')
- self.assertEqual(numbers.format_decimal(1.1, '@@@@@##', locale='sv'),
+ self.assertEqual(numbers.format_decimal(1.1, '@@@@@##', locale='sv'),
'1,1000')
- self.assertEqual(numbers.format_decimal(0.0001, '@@@', locale='sv'),
+ self.assertEqual(numbers.format_decimal(0.0001, '@@@', locale='sv'),
'0,000100')
- self.assertEqual(numbers.format_decimal(0.0001234, '@@@', locale='sv'),
+ self.assertEqual(numbers.format_decimal(0.0001234, '@@@', locale='sv'),
'0,000123')
- self.assertEqual(numbers.format_decimal(0.0001234, '@@@#',locale='sv'),
+ self.assertEqual(numbers.format_decimal(0.0001234, '@@@#',locale='sv'),
'0,0001234')
- self.assertEqual(numbers.format_decimal(0.0001234, '@@@#',locale='sv'),
+ self.assertEqual(numbers.format_decimal(0.0001234, '@@@#',locale='sv'),
'0,0001234')
- self.assertEqual(numbers.format_decimal(0.12345, '@@@',locale='sv'),
+ self.assertEqual(numbers.format_decimal(0.12345, '@@@',locale='sv'),
'0,123')
- self.assertEqual(numbers.format_decimal(3.14159, '@@##',locale='sv'),
+ self.assertEqual(numbers.format_decimal(3.14159, '@@##',locale='sv'),
'3,142')
- self.assertEqual(numbers.format_decimal(1.23004, '@@##',locale='sv'),
+ self.assertEqual(numbers.format_decimal(1.23004, '@@##',locale='sv'),
'1,23')
- self.assertEqual(numbers.format_decimal(1230.04, '@@,@@',locale='en_US'),
+ self.assertEqual(numbers.format_decimal(1230.04, '@@,@@',locale='en_US'),
'12,30')
- self.assertEqual(numbers.format_decimal(123.41, '@@##',locale='en_US'),
+ self.assertEqual(numbers.format_decimal(123.41, '@@##',locale='en_US'),
'123.4')
- self.assertEqual(numbers.format_decimal(1, '@@',locale='en_US'),
+ self.assertEqual(numbers.format_decimal(1, '@@',locale='en_US'),
'1.0')
- self.assertEqual(numbers.format_decimal(0, '@',locale='en_US'),
+ self.assertEqual(numbers.format_decimal(0, '@',locale='en_US'),
'0')
- self.assertEqual(numbers.format_decimal(0.1, '@',locale='en_US'),
+ self.assertEqual(numbers.format_decimal(0.1, '@',locale='en_US'),
'0.1')
- self.assertEqual(numbers.format_decimal(0.1, '@#',locale='en_US'),
+ self.assertEqual(numbers.format_decimal(0.1, '@#',locale='en_US'),
'0.1')
- self.assertEqual(numbers.format_decimal(0.1, '@@', locale='en_US'),
+ self.assertEqual(numbers.format_decimal(0.1, '@@', locale='en_US'),
'0.10')
def test_decimals(self):
"""Test significant digits patterns"""
- self.assertEqual(numbers.format_decimal(Decimal('1.2345'),
- '#.00', locale='en_US'),
+ self.assertEqual(numbers.format_decimal(Decimal('1.2345'),
+ '#.00', locale='en_US'),
'1.23')
- self.assertEqual(numbers.format_decimal(Decimal('1.2345000'),
- '#.00', locale='en_US'),
+ self.assertEqual(numbers.format_decimal(Decimal('1.2345000'),
+ '#.00', locale='en_US'),
'1.23')
- self.assertEqual(numbers.format_decimal(Decimal('1.2345000'),
- '@@', locale='en_US'),
+ self.assertEqual(numbers.format_decimal(Decimal('1.2345000'),
+ '@@', locale='en_US'),
'1.2')
- self.assertEqual(numbers.format_decimal(Decimal('12345678901234567890.12345'),
- '#.00', locale='en_US'),
+ self.assertEqual(numbers.format_decimal(Decimal('12345678901234567890.12345'),
+ '#.00', locale='en_US'),
'12345678901234567890.12')
def test_scientific_notation(self):
@@ -135,13 +135,13 @@ class FormatDecimalTestCase(unittest.TestCase):
self.assertEqual(fmt, '1.23E02 m/s')
fmt = numbers.format_scientific(0.012345, '#.##E00 m/s', locale='en_US')
self.assertEqual(fmt, '1.23E-02 m/s')
- fmt = numbers.format_scientific(Decimal('12345'), '#.##E+00 m/s',
+ fmt = numbers.format_scientific(Decimal('12345'), '#.##E+00 m/s',
locale='en_US')
self.assertEqual(fmt, '1.23E+04 m/s')
# 0 (see ticket #99)
fmt = numbers.format_scientific(0, '#E0', locale='en_US')
self.assertEqual(fmt, '0E0')
-
+
def test_formatting_of_very_small_decimals(self):
# previously formatting very small decimals could lead to a type error
# because the Decimal->string conversion was too simple (see #214)
@@ -153,7 +153,7 @@ class FormatDecimalTestCase(unittest.TestCase):
class BankersRoundTestCase(unittest.TestCase):
def test_round_to_nearest_integer(self):
self.assertEqual(1, numbers.bankersround(Decimal('0.5001')))
-
+
def test_round_to_even_for_two_nearest_integers(self):
self.assertEqual(0, numbers.bankersround(Decimal('0.5')))
self.assertEqual(2, numbers.bankersround(Decimal('1.5')))
@@ -165,22 +165,22 @@ class BankersRoundTestCase(unittest.TestCase):
class NumberParsingTestCase(unittest.TestCase):
def test_can_parse_decimals(self):
- self.assertEqual(Decimal('1099.98'),
+ self.assertEqual(Decimal('1099.98'),
numbers.parse_decimal('1,099.98', locale='en_US'))
- self.assertEqual(Decimal('1099.98'),
+ self.assertEqual(Decimal('1099.98'),
numbers.parse_decimal('1.099,98', locale='de'))
- self.assertRaises(numbers.NumberFormatError,
+ self.assertRaises(numbers.NumberFormatError,
lambda: numbers.parse_decimal('2,109,998', locale='de'))
def suite():
suite = unittest.TestSuite()
if sys.version_info >= (2, 5):
- # repr(Decimal(...)) was changed 2.5
+ # repr(Decimal(...)) was changed 2.5
# Python 2.4: Decimal("1")
# Python 2.5+: Decimal('1')
- # as the actual functionality is tested by unit tests, I don't see a
- # point in adding ugly workarounds in the doctests so just disable
+ # as the actual functionality is tested by unit tests, I don't see a
+ # point in adding ugly workarounds in the doctests so just disable
# these doctests for 2.4
suite.addTest(doctest.DocTestSuite(numbers))
suite.addTest(unittest.makeSuite(FormatDecimalTestCase))
diff --git a/babel/tests/support.py b/babel/tests/support.py
index cf006a9..00b8f18 100644
--- a/babel/tests/support.py
+++ b/babel/tests/support.py
@@ -24,7 +24,7 @@ from babel.messages import Catalog
from babel.messages.mofile import write_mo
class TranslationsTestCase(unittest.TestCase):
-
+
def setUp(self):
# Use a locale which won't fail to run the tests
os.environ['LANG'] = 'en_US.UTF-8'
@@ -43,7 +43,7 @@ class TranslationsTestCase(unittest.TestCase):
catalog1 = Catalog(locale='en_GB', domain='messages')
catalog2 = Catalog(locale='en_GB', domain='messages1')
for ids, kwargs in messages1:
- catalog1.add(ids, **kwargs)
+ catalog1.add(ids, **kwargs)
for ids, kwargs in messages2:
catalog2.add(ids, **kwargs)
catalog1_fp = StringIO()
@@ -165,7 +165,7 @@ class TranslationsTestCase(unittest.TestCase):
self.assertEqualTypeToo(
'VohsCTXD1', self.translations.ldnpgettext('messages1', 'foo', 'foo1',
'foos1', 2))
-
+
def test_load(self):
tempdir = tempfile.mkdtemp()
try:
@@ -174,7 +174,7 @@ class TranslationsTestCase(unittest.TestCase):
catalog = Catalog(locale='fr', domain='messages')
catalog.add('foo', 'bar')
write_mo(file(os.path.join(messages_dir, 'messages.mo'), 'wb'), catalog)
-
+
translations = support.Translations.load(tempdir, locales=('fr',), domain='messages')
self.assertEqual('bar', translations.gettext('foo'))
finally:
@@ -188,23 +188,23 @@ class NullTranslationsTestCase(unittest.TestCase):
fp.seek(0)
self.translations = support.Translations(fp=fp)
self.null_translations = support.NullTranslations(fp=fp)
-
+
def method_names(self):
return [name for name in dir(self.translations) if 'gettext' in name]
-
+
def test_same_methods(self):
for name in self.method_names():
if not hasattr(self.null_translations, name):
self.fail('NullTranslations does not provide method %r' % name)
-
+
def test_method_signature_compatibility(self):
for name in self.method_names():
translations_method = getattr(self.translations, name)
null_method = getattr(self.null_translations, name)
signature = inspect.getargspec
- self.assertEqual(signature(translations_method),
+ self.assertEqual(signature(translations_method),
signature(null_method))
-
+
def test_same_return_values(self):
data = {
'message': u'foo', 'domain': u'domain', 'context': 'tests',
@@ -229,7 +229,7 @@ class LazyProxyTestCase(unittest.TestCase):
proxy = support.LazyProxy(add_one)
self.assertEqual(1, proxy.value)
self.assertEqual(1, proxy.value)
-
+
def test_can_disable_proxy_cache(self):
self.counter = 0
def add_one():
diff --git a/babel/util.py b/babel/util.py
index 18924d0..14e8384 100644
--- a/babel/util.py
+++ b/babel/util.py
@@ -101,29 +101,29 @@ def parse_encoding(fp):
def pathmatch(pattern, filename):
"""Extended pathname pattern matching.
-
+
This function is similar to what is provided by the ``fnmatch`` module in
the Python standard library, but:
-
+
* can match complete (relative or absolute) path names, and not just file
names, and
* also supports a convenience pattern ("**") to match files at any
directory level.
-
+
Examples:
-
+
>>> pathmatch('**.py', 'bar.py')
True
>>> pathmatch('**.py', 'foo/bar/baz.py')
True
>>> pathmatch('**.py', 'templates/index.html')
False
-
+
>>> pathmatch('**/templates/*.html', 'templates/index.html')
True
>>> pathmatch('**/templates/*.html', 'templates/foo/bar.html')
False
-
+
:param pattern: the glob pattern
:param filename: the path name of the file to match against
:return: `True` if the path name matches the pattern, `False` otherwise
@@ -157,7 +157,7 @@ class TextWrapper(textwrap.TextWrapper):
def wraptext(text, width=70, initial_indent='', subsequent_indent=''):
"""Simple wrapper around the ``textwrap.wrap`` function in the standard
library. This version does not wrap lines on hyphens in words.
-
+
:param text: the text to wrap
:param width: the maximum line width
:param initial_indent: string that will be prepended to the first line of
@@ -175,7 +175,7 @@ def wraptext(text, width=70, initial_indent='', subsequent_indent=''):
class odict(dict):
"""Ordered dict implementation.
-
+
:see: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/107747
"""
def __init__(self, data=None):
@@ -246,14 +246,14 @@ try:
except AttributeError:
def relpath(path, start='.'):
"""Compute the relative path to one path from another.
-
+
>>> relpath('foo/bar.txt', '').replace(os.sep, '/')
'foo/bar.txt'
>>> relpath('foo/bar.txt', 'foo').replace(os.sep, '/')
'bar.txt'
>>> relpath('foo/bar.txt', 'baz').replace(os.sep, '/')
'../foo/bar.txt'
-
+
:return: the relative path
:rtype: `basestring`
"""
@@ -299,7 +299,7 @@ try:
except ImportError:
UTC = FixedOffsetTimezone(0, 'UTC')
"""`tzinfo` object for UTC (Universal Time).
-
+
:type: `tzinfo`
"""