[+] NestedAccessor
[+] support __getattr__ [+] support some.key.here
This commit is contained in:
parent
6a0347e7c4
commit
cf50296264
@ -4,11 +4,34 @@ from collections import defaultdict
|
||||
import json5
|
||||
from loguru import logger
|
||||
|
||||
from . import utils
|
||||
try:
|
||||
from . import utils
|
||||
except ImportError:
|
||||
import utils
|
||||
|
||||
log = logger.bind(module="i18n", prefix="init")
|
||||
log_load = logger.bind(module="i18n", prefix="load")
|
||||
|
||||
|
||||
class NestedAccessor:
|
||||
def __init__(self, parent, key_chain):
|
||||
self.parent: "I18N" = parent
|
||||
self.key_chain = key_chain
|
||||
|
||||
def __getattr__(self, item):
|
||||
return NestedAccessor(self.parent, self.key_chain + [item]) # Продолжаем цепочку
|
||||
|
||||
def __call__(self, **kwargs):
|
||||
key = ".".join(self.key_chain)
|
||||
return self.parent.get_phrase(key, **kwargs)
|
||||
|
||||
def __str__(self):
|
||||
return self()
|
||||
|
||||
def __repr__(self):
|
||||
return f"<NestedAccessor key={'.'.join(self.key_chain)}>"
|
||||
|
||||
|
||||
class I18N:
|
||||
|
||||
def __init__(self, locale_dir, load_lang, encoding):
|
||||
@ -29,6 +52,10 @@ class I18N:
|
||||
log.debug("Ready")
|
||||
self._load()
|
||||
|
||||
@property
|
||||
def locale(self):
|
||||
return self._locale
|
||||
|
||||
def _load(self):
|
||||
if not self._locale_dir:
|
||||
raise FileNotFoundError(f"Locale directory not found: {self._locale_dir}")
|
||||
@ -63,11 +90,31 @@ class I18N:
|
||||
# key: some.key.here
|
||||
phrase = self._locale.get(key)
|
||||
if not phrase:
|
||||
return key.upper()
|
||||
return phrase.format_map(defaultdict(lambda: '???', kwargs))
|
||||
return f"<{key.upper()}>"
|
||||
return phrase.format_map(defaultdict(lambda: '<unknown>', kwargs))
|
||||
|
||||
def __getattr__(self, item):
|
||||
key = item.replace("_", ".") # заменяем _ на . для удобства
|
||||
return NestedAccessor(self, [key]) # Начинаем цепочку
|
||||
|
||||
def __setattr__(self, key, value):
|
||||
raise AttributeError("Can't set attribute")
|
||||
|
||||
def __call__(self, key: str, **kwargs):
|
||||
return self.get_phrase(key, **kwargs)
|
||||
|
||||
def __getitem__(self, key: str):
|
||||
return self.get_phrase(key)
|
||||
|
||||
if __name__ == '__main__':
|
||||
i18n = I18N("", "ru", "utf-8")
|
||||
print(1, i18n.get_phrase("some.key.here", name="John"))
|
||||
print(2, i18n("some.key.here", name="John"))
|
||||
print(3, i18n["some.key.here"])
|
||||
|
||||
print(4, i18n.some_key_here(name="John"))
|
||||
print(5, i18n.some_key_here)
|
||||
print(6, i18n.some.key.here(name="John"))
|
||||
print(7, i18n.some.key.here)
|
||||
|
||||
print(8, i18n.some.key.no.registered)
|
||||
|
Loading…
x
Reference in New Issue
Block a user