summaryrefslogtreecommitdiff
path: root/sphinx/locale/__init__.py
diff options
context:
space:
mode:
Diffstat (limited to 'sphinx/locale/__init__.py')
-rw-r--r--sphinx/locale/__init__.py84
1 files changed, 71 insertions, 13 deletions
diff --git a/sphinx/locale/__init__.py b/sphinx/locale/__init__.py
index d6ce7329b..7c0f9b4f9 100644
--- a/sphinx/locale/__init__.py
+++ b/sphinx/locale/__init__.py
@@ -14,6 +14,10 @@ import gettext
from six import PY3, text_type
from six.moves import UserString
+if False:
+ # For type annotation
+ from typing import Any, Callable, Dict, Iterator, List, Tuple # NOQA
+
class _TranslationProxy(UserString, object):
"""
@@ -31,24 +35,31 @@ class _TranslationProxy(UserString, object):
__slots__ = ('_func', '_args')
def __new__(cls, func, *args):
+ # type: (Callable, unicode) -> object
if not args:
# not called with "function" and "arguments", but a plain string
return text_type(func)
- return object.__new__(cls)
+ return object.__new__(cls) # type: ignore
def __getnewargs__(self):
- return (self._func,) + self._args
+ # type: () -> Tuple
+ return (self._func,) + self._args # type: ignore
def __init__(self, func, *args):
+ # type: (Callable, unicode) -> None
self._func = func
self._args = args
- data = property(lambda x: x._func(*x._args))
+ @property
+ def data(self):
+ # type: () -> unicode
+ return self._func(*self._args)
# replace function from UserString; it instantiates a self.__class__
# for the encoding result
def encode(self, encoding=None, errors=None):
+ # type: (unicode, unicode) -> str
if encoding:
if errors:
return self.data.encode(encoding, errors)
@@ -58,81 +69,106 @@ class _TranslationProxy(UserString, object):
return self.data.encode()
def __contains__(self, key):
+ # type: (Any) -> bool
return key in self.data
def __bool__(self):
+ # type: () -> bool
return bool(self.data)
__nonzero__ = __bool__ # for python2 compatibility
def __dir__(self):
+ # type: () -> List[str]
return dir(text_type)
def __iter__(self):
+ # type: () -> Iterator[unicode]
return iter(self.data)
def __len__(self):
+ # type: () -> int
return len(self.data)
def __str__(self):
+ # type: () -> str
return str(self.data)
def __unicode__(self):
+ # type: () -> unicode
return text_type(self.data)
def __add__(self, other):
+ # type: (unicode) -> unicode
return self.data + other
def __radd__(self, other):
+ # type: (unicode) -> unicode
return other + self.data
def __mod__(self, other):
+ # type: (unicode) -> unicode
return self.data % other
def __rmod__(self, other):
+ # type: (unicode) -> unicode
return other % self.data
def __mul__(self, other):
+ # type: (Any) -> unicode
return self.data * other
def __rmul__(self, other):
+ # type: (Any) -> unicode
return other * self.data
def __lt__(self, other):
+ # type: (unicode) -> bool
return self.data < other
def __le__(self, other):
+ # type: (unicode) -> bool
return self.data <= other
def __eq__(self, other):
+ # type: (Any) -> bool
return self.data == other
def __ne__(self, other):
+ # type: (Any) -> bool
return self.data != other
def __gt__(self, other):
+ # type: (unicode) -> bool
return self.data > other
def __ge__(self, other):
+ # type: (unicode) -> bool
return self.data >= other
def __getattr__(self, name):
+ # type: (unicode) -> Any
if name == '__members__':
return self.__dir__()
return getattr(self.data, name)
def __getstate__(self):
+ # type: () -> Tuple[Callable, Tuple[unicode, ...]]
return self._func, self._args
def __setstate__(self, tup):
+ # type: (Tuple[Callable, Tuple[unicode]]) -> None
self._func, self._args = tup
def __getitem__(self, key):
+ # type: (Any) -> unicode
return self.data[key]
def __copy__(self):
+ # type: () -> _TranslationProxy
return self
def __repr__(self):
+ # type: () -> str
try:
return 'i' + repr(text_type(self.data))
except:
@@ -140,6 +176,7 @@ class _TranslationProxy(UserString, object):
def mygettext(string):
+ # type: (unicode) -> unicode
"""Used instead of _ when creating TranslationProxies, because _ is
not bound yet at that time.
"""
@@ -147,10 +184,11 @@ def mygettext(string):
def lazy_gettext(string):
+ # type: (unicode) -> unicode
"""A lazy version of `gettext`."""
# if isinstance(string, _TranslationProxy):
# return string
- return _TranslationProxy(mygettext, string)
+ return _TranslationProxy(mygettext, string) # type: ignore
l_ = lazy_gettext
@@ -167,13 +205,13 @@ admonitionlabels = {
'seealso': l_('See also'),
'tip': l_('Tip'),
'warning': l_('Warning'),
-}
+} # type: Dict[unicode, unicode]
versionlabels = {
'versionadded': l_('New in version %s'),
'versionchanged': l_('Changed in version %s'),
'deprecated': l_('Deprecated since version %s'),
-}
+} # type: Dict[unicode, unicode]
# XXX Python specific
pairindextypes = {
@@ -184,19 +222,28 @@ pairindextypes = {
'exception': l_('exception'),
'statement': l_('statement'),
'builtin': l_('built-in function'),
-}
+} # Dict[unicode, _TranslationProxy]
-translators = {}
+translators = {} # type: Dict[unicode, Any]
if PY3:
def _(message):
- return translators['sphinx'].gettext(message)
+ # type: (unicode) -> unicode
+ try:
+ return translators['sphinx'].gettext(message)
+ except KeyError:
+ return message
else:
def _(message):
- return translators['sphinx'].ugettext(message)
+ # type: (unicode) -> unicode
+ try:
+ return translators['sphinx'].ugettext(message)
+ except KeyError:
+ return message
def init(locale_dirs, language, catalog='sphinx'):
+ # type: (List, unicode, unicode) -> Tuple[Any, bool]
"""Look for message catalogs in `locale_dirs` and *ensure* that there is at
least a NullTranslations catalog set in `translators`. If called multiple
times or if several ``.mo`` files are found, their contents are merged
@@ -213,12 +260,12 @@ def init(locale_dirs, language, catalog='sphinx'):
# loading
for dir_ in locale_dirs:
try:
- trans = gettext.translation(catalog, localedir=dir_,
- languages=[language])
+ trans = gettext.translation(catalog, localedir=dir_, # type: ignore
+ languages=[language]) # type: ignore
if translator is None:
translator = trans
else:
- translator._catalog.update(trans._catalog)
+ translator._catalog.update(trans._catalog) # type: ignore
except Exception:
# Language couldn't be found in the specified path
pass
@@ -230,3 +277,14 @@ def init(locale_dirs, language, catalog='sphinx'):
if hasattr(translator, 'ugettext'):
translator.gettext = translator.ugettext
return translator, has_translation
+
+
+def get_translator(catalog='sphinx'):
+ # type: (unicode) -> gettext.NullTranslations
+ global translators
+ translator = translators.get(catalog)
+ if translator is None:
+ translator = gettext.NullTranslations()
+ if hasattr(translator, 'ugettext'):
+ translator.gettext = translator.ugettext
+ return translator