jenkins-bot submitted this change.

View Change

Approvals: Mpaa: Looks good to me, approved jenkins-bot: Verified
[IMPR] Use functools.cache for i18n._get_translation function

Change-Id: Ie6ce6479069a624858e52862f7517b64adc8399f
---
M pywikibot/i18n.py
1 file changed, 11 insertions(+), 14 deletions(-)

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):

To view, visit change 629139. To unsubscribe, or for help writing mail filters, visit settings.

Gerrit-Project: pywikibot/core
Gerrit-Branch: master
Gerrit-Change-Id: Ie6ce6479069a624858e52862f7517b64adc8399f
Gerrit-Change-Number: 629139
Gerrit-PatchSet: 1
Gerrit-Owner: Xqt <info@gno.de>
Gerrit-Reviewer: Isaacandy <isaac@iznd.xyz>
Gerrit-Reviewer: Mpaa <mpaa.wiki@gmail.com>
Gerrit-Reviewer: Siebrand <siebrand@kitano.nl>
Gerrit-Reviewer: jenkins-bot
Gerrit-MessageType: merged