Package babel :: Module core

Module core



Core locale representation and locale data access.

Classes
  UnknownLocaleError
Exception thrown when a locale is requested for which no locale data is available.
  Locale
Representation of a specific locale.
Functions
str
default_locale(category=None)
Returns the system default locale for a given category, based on environment variables.
str
negotiate_locale(preferred, available, sep='_')
Find the best match between available and requested locale strings.
tuple
parse_locale(identifier, sep='_')
Parse a locale identifier into a tuple of the form:
Function Details

default_locale(category=None)

 

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'
>>> default_locale('LC_MESSAGES')
'fr_FR'
Parameters:
  • category - one of the LC_XXX environment variable names
Returns: str
the value of the variable, or any of the fallbacks (LANGUAGE, LC_ALL, LC_CTYPE, and LANG)

negotiate_locale(preferred, available, sep='_')

 

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'
Parameters:
  • preferred - the list of locale strings preferred by the user
  • available - the list of locale strings available
  • sep - character that separates the different parts of the locale strings
Returns: str
the locale identifier for the best match, or None if no match was found

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
Parameters:
  • identifier - the locale identifier string
  • sep - character that separates the different components of the locale identifier
Returns: tuple
the (language, territory, script, variant) tuple
Raises:
  • ValueError - if the string does not appear to be a valid locale identifier

See Also: IETF RFC 4646