summaryrefslogtreecommitdiff
path: root/django/utils/translation/__init__.py
diff options
context:
space:
mode:
Diffstat (limited to 'django/utils/translation/__init__.py')
-rw-r--r--django/utils/translation/__init__.py98
1 files changed, 65 insertions, 33 deletions
diff --git a/django/utils/translation/__init__.py b/django/utils/translation/__init__.py
index 29ac60ad1d..6b8cc73d5c 100644
--- a/django/utils/translation/__init__.py
+++ b/django/utils/translation/__init__.py
@@ -9,14 +9,27 @@ from django.utils.functional import lazy
from django.utils.regex_helper import _lazy_re_compile
__all__ = [
- 'activate', 'deactivate', 'override', 'deactivate_all',
- 'get_language', 'get_language_from_request',
- 'get_language_info', 'get_language_bidi',
- 'check_for_language', 'to_language', 'to_locale', 'templatize',
- 'gettext', 'gettext_lazy', 'gettext_noop',
- 'ngettext', 'ngettext_lazy',
- 'pgettext', 'pgettext_lazy',
- 'npgettext', 'npgettext_lazy',
+ "activate",
+ "deactivate",
+ "override",
+ "deactivate_all",
+ "get_language",
+ "get_language_from_request",
+ "get_language_info",
+ "get_language_bidi",
+ "check_for_language",
+ "to_language",
+ "to_locale",
+ "templatize",
+ "gettext",
+ "gettext_lazy",
+ "gettext_noop",
+ "ngettext",
+ "ngettext_lazy",
+ "pgettext",
+ "pgettext_lazy",
+ "npgettext",
+ "npgettext_lazy",
]
@@ -32,6 +45,7 @@ class TranslatorCommentWarning(SyntaxWarning):
# replace the functions with their real counterparts (once we do access the
# settings).
+
class Trans:
"""
The purpose of this class is to store the actual translation function upon
@@ -47,13 +61,20 @@ class Trans:
def __getattr__(self, real_name):
from django.conf import settings
+
if settings.USE_I18N:
from django.utils.translation import trans_real as trans
from django.utils.translation.reloader import (
- translation_file_changed, watch_for_translation_changes,
+ translation_file_changed,
+ watch_for_translation_changes,
+ )
+
+ autoreload_started.connect(
+ watch_for_translation_changes, dispatch_uid="translation_file_changed"
+ )
+ file_changed.connect(
+ translation_file_changed, dispatch_uid="translation_file_changed"
)
- autoreload_started.connect(watch_for_translation_changes, dispatch_uid='translation_file_changed')
- file_changed.connect(translation_file_changed, dispatch_uid='translation_file_changed')
else:
from django.utils.translation import trans_null as trans
setattr(self, real_name, getattr(trans, real_name))
@@ -92,31 +113,33 @@ pgettext_lazy = lazy(pgettext, str)
def lazy_number(func, resultclass, number=None, **kwargs):
if isinstance(number, int):
- kwargs['number'] = number
+ kwargs["number"] = number
proxy = lazy(func, resultclass)(**kwargs)
else:
original_kwargs = kwargs.copy()
class NumberAwareString(resultclass):
def __bool__(self):
- return bool(kwargs['singular'])
+ return bool(kwargs["singular"])
def _get_number_value(self, values):
try:
return values[number]
except KeyError:
raise KeyError(
- "Your dictionary lacks key '%s\'. Please provide "
+ "Your dictionary lacks key '%s'. Please provide "
"it, because it is required to determine whether "
"string is singular or plural." % number
)
def _translate(self, number_value):
- kwargs['number'] = number_value
+ kwargs["number"] = number_value
return func(**kwargs)
def format(self, *args, **kwargs):
- number_value = self._get_number_value(kwargs) if kwargs and number else args[0]
+ number_value = (
+ self._get_number_value(kwargs) if kwargs and number else args[0]
+ )
return self._translate(number_value).format(*args, **kwargs)
def __mod__(self, rhs):
@@ -133,7 +156,10 @@ def lazy_number(func, resultclass, number=None, **kwargs):
return translated
proxy = lazy(lambda **kwargs: NumberAwareString(), NumberAwareString)(**kwargs)
- proxy.__reduce__ = lambda: (_lazy_number_unpickle, (func, resultclass, number, original_kwargs))
+ proxy.__reduce__ = lambda: (
+ _lazy_number_unpickle,
+ (func, resultclass, number, original_kwargs),
+ )
return proxy
@@ -146,7 +172,9 @@ def ngettext_lazy(singular, plural, number=None):
def npgettext_lazy(context, singular, plural, number=None):
- return lazy_number(npgettext, str, context=context, singular=singular, plural=plural, number=number)
+ return lazy_number(
+ npgettext, str, context=context, singular=singular, plural=plural, number=number
+ )
def activate(language):
@@ -192,27 +220,27 @@ def check_for_language(lang_code):
def to_language(locale):
"""Turn a locale name (en_US) into a language name (en-us)."""
- p = locale.find('_')
+ p = locale.find("_")
if p >= 0:
- return locale[:p].lower() + '-' + locale[p + 1:].lower()
+ return locale[:p].lower() + "-" + locale[p + 1 :].lower()
else:
return locale.lower()
def to_locale(language):
"""Turn a language name (en-us) into a locale name (en_US)."""
- lang, _, country = language.lower().partition('-')
+ lang, _, country = language.lower().partition("-")
if not country:
return language[:3].lower() + language[3:]
# A language with > 2 characters after the dash only has its first
# character after the dash capitalized; e.g. sr-latn becomes sr_Latn.
# A language with 2 characters after the dash has both characters
# capitalized; e.g. en-us becomes en_US.
- country, _, tail = country.partition('-')
+ country, _, tail = country.partition("-")
country = country.title() if len(country) > 2 else country.upper()
if tail:
- country += '-' + tail
- return lang + '_' + country
+ country += "-" + tail
+ return lang + "_" + country
def get_language_from_request(request, check_path=False):
@@ -229,6 +257,7 @@ def get_supported_language_variant(lang_code, *, strict=False):
def templatize(src, **kwargs):
from .template import templatize
+
return templatize(src, **kwargs)
@@ -238,32 +267,35 @@ def deactivate_all():
def get_language_info(lang_code):
from django.conf.locale import LANG_INFO
+
try:
lang_info = LANG_INFO[lang_code]
- if 'fallback' in lang_info and 'name' not in lang_info:
- info = get_language_info(lang_info['fallback'][0])
+ if "fallback" in lang_info and "name" not in lang_info:
+ info = get_language_info(lang_info["fallback"][0])
else:
info = lang_info
except KeyError:
- if '-' not in lang_code:
+ if "-" not in lang_code:
raise KeyError("Unknown language code %s." % lang_code)
- generic_lang_code = lang_code.split('-')[0]
+ generic_lang_code = lang_code.split("-")[0]
try:
info = LANG_INFO[generic_lang_code]
except KeyError:
- raise KeyError("Unknown language code %s and %s." % (lang_code, generic_lang_code))
+ raise KeyError(
+ "Unknown language code %s and %s." % (lang_code, generic_lang_code)
+ )
if info:
- info['name_translated'] = gettext_lazy(info['name'])
+ info["name_translated"] = gettext_lazy(info["name"])
return info
-trim_whitespace_re = _lazy_re_compile(r'\s*\n\s*')
+trim_whitespace_re = _lazy_re_compile(r"\s*\n\s*")
def trim_whitespace(s):
- return trim_whitespace_re.sub(' ', s.strip())
+ return trim_whitespace_re.sub(" ", s.strip())
def round_away_from_one(value):
- return int(Decimal(value - 1).quantize(Decimal('0'), rounding=ROUND_UP)) + 1
+ return int(Decimal(value - 1).quantize(Decimal("0"), rounding=ROUND_UP)) + 1