jenkins-bot has submitted this change. ( https://gerrit.wikimedia.org/r/c/pywikibot/core/+/629139 )
Change subject: [IMPR] Use functools.cache for i18n._get_translation function ......................................................................
[IMPR] Use functools.cache for i18n._get_translation function
Change-Id: Ie6ce6479069a624858e52862f7517b64adc8399f --- M pywikibot/i18n.py 1 file changed, 11 insertions(+), 14 deletions(-)
Approvals: Mpaa: Looks good to me, approved jenkins-bot: Verified
diff --git a/pywikibot/i18n.py b/pywikibot/i18n.py index 9779f83..99fe2e3 100644 --- a/pywikibot/i18n.py +++ b/pywikibot/i18n.py @@ -38,7 +38,13 @@ from pywikibot.exceptions import Error from pywikibot.plural import plural_rules from pywikibot.tools import ( - deprecated, deprecated_args, issue_deprecation_warning) + deprecated, deprecated_args, issue_deprecation_warning, PYTHON_VERSION) + +if PYTHON_VERSION >= (3, 9, 0): + from functools import cache +else: + from functools import lru_cache + cache = lru_cache(None)
PLURAL_PATTERN = r'{{PLURAL:(?:%()?([^)]*?)(?:)d)?|(.*?)}}'
@@ -50,10 +56,6 @@ # Flag to indicate whether translation messages are available _messages_available = None
-# Cache of translated messages -_cache = defaultdict(dict) - - _LANG_TO_GROUP_NAME = defaultdict(str, { 'aa': 'aa', 'ab': 'ab', @@ -421,28 +423,23 @@ pass
+@cache def _get_translation(lang, twtitle): """ Return message of certain twtitle if exists.
For internal use, don't use it directly. """ - if twtitle in _cache[lang]: - return _cache[lang][twtitle] message_bundle = twtitle.split('-')[0] - filename = '%s/%s.json' % (message_bundle, lang) + filename = '{}/{}.json'.format(message_bundle, lang) try: trans_text = pkgutil.get_data( _messages_package_name, filename).decode('utf-8') except (OSError, IOError): # file open can cause several exceptions - _cache[lang][twtitle] = None return None + transdict = json.loads(trans_text) - _cache[lang].update(transdict) - try: - return transdict[twtitle] - except KeyError: - return None + return transdict.get(twtitle)
def _extract_plural(code, message, parameters):