Skip to content

Documentation for PyI18n class

Main i18n localization class

Attributes:

Name Type Description
available_locales tuple

list of available locales

load_path str

path to locales directory

_loaded_translations dict

(class attribute) dictionary of loaded translations

Examples:

>>> from pyi18n import PyI18n
>>> pyi18n = PyI18n(("en", "jp"), "locales/")
>>> pyi18n.gettext("en", "hello.world")
'Hello, world!'
>>> pyi18n.gettext("jp", "hello.world")
'こんにちは、世界!'
Source code in pyi18n/pyi18n.py
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
class PyI18n:
    """ Main i18n localization class

    Attributes:
        available_locales (tuple): list of available locales
        load_path (str): path to locales directory
        _loaded_translations (dict): (class attribute) dictionary
                                    of loaded translations

    Examples:
        >>> from pyi18n import PyI18n
        >>> pyi18n = PyI18n(("en", "jp"), "locales/")
        >>> pyi18n.gettext("en", "hello.world")
        'Hello, world!'
        >>> pyi18n.gettext("jp", "hello.world")
        'こんにちは、世界!'
    """

    _loaded_translations: dict = {}

    def __init__(self,
                 available_locales: tuple,
                 load_path: str = "locales/",
                 loader: PyI18nBaseLoader = None
                 ) -> None:

        """ Initialize i18n class

        Args:
            available_locales (tuple): list of available locales
            load_path (str): path to locales directory

        Return:
            None
        """

        self.available_locales: tuple = available_locales
        self.load_path: str = f"{getcwd()}/{load_path}"
        self.loader: PyI18nBaseLoader = loader or PyI18nYamlLoader(
            self.load_path)

        self.load_path: str = self.loader.get_path() if self.loader.get_path(
        ) != self.load_path else self.load_path

        self.__pyi18n_init()

    def __pyi18n_init(self) -> None:
        """ validator and loader for translations

        Raises:
            ValueError: if locale is not available in self.available_locales
            FileNotFoundError: if translation file is not found

        """

        if not self.available_locales:
            raise ValueError("available locales must be specified")

        if not exists(self.load_path):
            raise FileNotFoundError(f"{self.load_path} directory "
                                    "not found, please create it")

        self._loaded_translations: dict = self.loader.load(
                                            self.available_locales)

    def gettext(self, locale: str, path: str, **kwargs) -> Union[dict, str]:
        """ Get translation for given locale and path

        Args:
            locale (str): locale to get translation for
            path (str): path to translation
            **kwargs (dict): interpolation variables

        Returns:
            Union[dict, str]: translation str, dict or error message

        Raises:
            ValueError: if locale is not in self.available_locales

        """

        if locale not in self.available_locales:
            raise ValueError(f"locale {locale} not specified "
                             "in available locales")

        founded: Union[dict, str] = self.__find(path, locale)

        if len(kwargs) > 0 and isinstance(founded, str):
            try:
                return founded.format_map(defaultdict(str, **kwargs))
            except KeyError:
                return founded
        return founded

    def __find(self, path: str, locale: str) -> Union[dict, str]:
        """ Find translation for given path and locale

        Args:
            path (str): path to translation
            locale (str): locale to get translation for

        Returns:
            Union[dict, str]: translation str, dict or error message

        """
        try:
            return reduce(getitem, path.split('.'),
                          self._loaded_translations[locale])
        except (KeyError, TypeError):
            return f"missing translation for: {locale}.{path}"

    def get_loader(self) -> PyI18nBaseLoader:
        """ Return loader class

        Returns:
            PyI18nBaseLoader: loader class

        """
        return self.loader

__find(path, locale)

Find translation for given path and locale

Parameters:

Name Type Description Default
path str

path to translation

required
locale str

locale to get translation for

required

Returns:

Type Description
Union[dict, str]

Union[dict, str]: translation str, dict or error message

Source code in pyi18n/pyi18n.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
def __find(self, path: str, locale: str) -> Union[dict, str]:
    """ Find translation for given path and locale

    Args:
        path (str): path to translation
        locale (str): locale to get translation for

    Returns:
        Union[dict, str]: translation str, dict or error message

    """
    try:
        return reduce(getitem, path.split('.'),
                      self._loaded_translations[locale])
    except (KeyError, TypeError):
        return f"missing translation for: {locale}.{path}"

__init__(available_locales, load_path='locales/', loader=None)

Initialize i18n class

Parameters:

Name Type Description Default
available_locales tuple

list of available locales

required
load_path str

path to locales directory

'locales/'
Return

None

Source code in pyi18n/pyi18n.py
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def __init__(self,
             available_locales: tuple,
             load_path: str = "locales/",
             loader: PyI18nBaseLoader = None
             ) -> None:

    """ Initialize i18n class

    Args:
        available_locales (tuple): list of available locales
        load_path (str): path to locales directory

    Return:
        None
    """

    self.available_locales: tuple = available_locales
    self.load_path: str = f"{getcwd()}/{load_path}"
    self.loader: PyI18nBaseLoader = loader or PyI18nYamlLoader(
        self.load_path)

    self.load_path: str = self.loader.get_path() if self.loader.get_path(
    ) != self.load_path else self.load_path

    self.__pyi18n_init()

__pyi18n_init()

validator and loader for translations

Raises:

Type Description
ValueError

if locale is not available in self.available_locales

FileNotFoundError

if translation file is not found

Source code in pyi18n/pyi18n.py
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
def __pyi18n_init(self) -> None:
    """ validator and loader for translations

    Raises:
        ValueError: if locale is not available in self.available_locales
        FileNotFoundError: if translation file is not found

    """

    if not self.available_locales:
        raise ValueError("available locales must be specified")

    if not exists(self.load_path):
        raise FileNotFoundError(f"{self.load_path} directory "
                                "not found, please create it")

    self._loaded_translations: dict = self.loader.load(
                                        self.available_locales)

get_loader()

Return loader class

Returns:

Name Type Description
PyI18nBaseLoader PyI18nBaseLoader

loader class

Source code in pyi18n/pyi18n.py
129
130
131
132
133
134
135
136
def get_loader(self) -> PyI18nBaseLoader:
    """ Return loader class

    Returns:
        PyI18nBaseLoader: loader class

    """
    return self.loader

gettext(locale, path, **kwargs)

Get translation for given locale and path

Parameters:

Name Type Description Default
locale str

locale to get translation for

required
path str

path to translation

required
**kwargs dict

interpolation variables

{}

Returns:

Type Description
Union[dict, str]

Union[dict, str]: translation str, dict or error message

Raises:

Type Description
ValueError

if locale is not in self.available_locales

Source code in pyi18n/pyi18n.py
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
def gettext(self, locale: str, path: str, **kwargs) -> Union[dict, str]:
    """ Get translation for given locale and path

    Args:
        locale (str): locale to get translation for
        path (str): path to translation
        **kwargs (dict): interpolation variables

    Returns:
        Union[dict, str]: translation str, dict or error message

    Raises:
        ValueError: if locale is not in self.available_locales

    """

    if locale not in self.available_locales:
        raise ValueError(f"locale {locale} not specified "
                         "in available locales")

    founded: Union[dict, str] = self.__find(path, locale)

    if len(kwargs) > 0 and isinstance(founded, str):
        try:
            return founded.format_map(defaultdict(str, **kwargs))
        except KeyError:
            return founded
    return founded