From 38d63e453f3bd0846f7b564829a4445e9528e929 Mon Sep 17 00:00:00 2001 From: Holden Nelson Date: Tue, 27 Oct 2020 12:50:01 -0600 Subject: [PATCH] Add ability to run code in a context with a temporary locale. Fix #1347 --- RELEASE.md | 3 +++ pelican/tests/test_utils.py | 8 ++++++++ pelican/utils.py | 14 ++++++++++++++ 3 files changed, 25 insertions(+) create mode 100644 RELEASE.md diff --git a/RELEASE.md b/RELEASE.md new file mode 100644 index 00000000..6b928a2a --- /dev/null +++ b/RELEASE.md @@ -0,0 +1,3 @@ +Release type: minor + +Add ability to run code in a context with a temporary locale. diff --git a/pelican/tests/test_utils.py b/pelican/tests/test_utils.py index 10816199..4faa30c4 100644 --- a/pelican/tests/test_utils.py +++ b/pelican/tests/test_utils.py @@ -593,6 +593,14 @@ class TestUtils(LoggedTestCase): utils.maybe_pluralize(2, 'Article', 'Articles'), '2 Articles') + def test_temporary_locale(self): + orig_locale = locale.setlocale(locale.LC_ALL) + + with utils.temporary_locale('C'): + self.assertEqual(locale.setlocale(locale.LC_ALL), 'C') + + self.assertEqual(locale.setlocale(locale.LC_ALL), orig_locale) + class TestCopy(unittest.TestCase): '''Tests the copy utility''' diff --git a/pelican/utils.py b/pelican/utils.py index e82117d3..5fca52ca 100644 --- a/pelican/utils.py +++ b/pelican/utils.py @@ -966,3 +966,17 @@ def maybe_pluralize(count, singular, plural): if count == 1: selection = singular return '{} {}'.format(count, selection) + + +@contextmanager +def temporary_locale(temp_locale=None): + ''' + Enable code to run in a context with a temporary locale + + Resets the locale back when exiting context. + ''' + orig_locale = locale.setlocale(locale.LC_ALL) + if temp_locale is not None: + locale.setlocale(locale.LC_ALL, temp_locale) + yield + locale.setlocale(locale.LC_ALL, orig_locale)