From 43dd5c70d16ae43623abe5d9926e084ea1fa3cc9 Mon Sep 17 00:00:00 2001 From: Paul Morelle Date: Tue, 27 Oct 2020 10:01:52 +0000 Subject: [PATCH] [IMP] translate: add add/radd methods on _lt class In order to ease the usage of lazy translation, add the possibility to add the _lt objects together and with strings. Adding two _lt objects together or to a string will execute their translation, so these operations still must be done once the user's language has been defined. For example, this is now possible: MESSAGES = { 1: _lt("Hello, world!"), 2: _lt("Lorem ipsum"), } def get_text(code): return _("Text is: ") + MESSAGES[code] closes odoo/odoo#60844 X-original-commit: c4596664e5514018c565eaf14b93e000d972bd30 Signed-off-by: Martin Trigaux (mat) Signed-off-by: Paul Morelle --- .../tests/test_term_count.py | 4 ++++ odoo/tools/translate.py | 16 ++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/odoo/addons/test_translation_import/tests/test_term_count.py b/odoo/addons/test_translation_import/tests/test_term_count.py index ce23a1b899d..38f1e7a75fa 100644 --- a/odoo/addons/test_translation_import/tests/test_term_count.py +++ b/odoo/addons/test_translation_import/tests/test_term_count.py @@ -205,6 +205,10 @@ class TestTermCount(common.TransactionCase): context = {'lang': "tlh"} self.assertEqual(str(TRANSLATED_TERM), "tlhIngan", "The lazy code translation was not applied") + self.assertEqual("Do you speak " + TRANSLATED_TERM, "Do you speak tlhIngan", "str + _lt concatenation failed") + self.assertEqual(TRANSLATED_TERM + ", I speak it", "tlhIngan, I speak it", "_lt + str concatenation failed") + self.assertEqual(TRANSLATED_TERM + TRANSLATED_TERM, "tlhIngantlhIngan", "_lt + _lt concatenation failed") + def test_import_from_csv_file(self): """Test the import from a single CSV file works""" with file_open('test_translation_import/i18n/dot.csv', 'rb') as f: diff --git a/odoo/tools/translate.py b/odoo/tools/translate.py index bb7f9fcea4b..eed29f7f784 100644 --- a/odoo/tools/translate.py +++ b/odoo/tools/translate.py @@ -539,6 +539,22 @@ class _lt: def __lt__(self, other): raise NotImplementedError() + def __add__(self, other): + # Call _._get_translation() like _() does, so that we have the same number + # of stack frames calling _get_translation() + if isinstance(other, str): + return _._get_translation(self._source) + other + elif isinstance(other, _lt): + return _._get_translation(self._source) + _._get_translation(other._source) + return NotImplemented + + def __radd__(self, other): + # Call _._get_translation() like _() does, so that we have the same number + # of stack frames calling _get_translation() + if isinstance(other, str): + return other + _._get_translation(self._source) + return NotImplemented + _ = GettextAlias()