Temporarily override locale with a context manager

前端 未结 3 912
有刺的猬
有刺的猬 2021-01-20 18:36

Is there a way to temporarily activate a locale within the scope of a block of code? Basically, I want to do something like this:

locale.setlocale(locale.LC_         


        
3条回答
  •  失恋的感觉
    2021-01-20 18:57

    You can write an easy and straight-forward contextmanager for this:

    from locale import getlocale, setlocale
    from contextlib import contextmanager
    
    
    @contextmanager
    def override_locale(category, locale_string):
        prev_locale_string = getlocale(category)
        setlocale(category, locale_string)
        yield
        setlocale(category, prev_locale_string)
    

提交回复
热议问题