Add ability to run code in a context with a temporary locale. Fix #1347

This commit is contained in:
Holden Nelson 2020-10-27 12:50:01 -06:00
commit 38d63e453f
3 changed files with 25 additions and 0 deletions

3
RELEASE.md Normal file
View file

@ -0,0 +1,3 @@
Release type: minor
Add ability to run code in a context with a temporary locale.

View file

@ -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'''

View file

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