@contextmanager
def set_locale(new_locale, lc_var=locale.LC_ALL):
 current_locale = locale.getlocale()
 try:
  locale.setlocale(lc_var, new_locale)
  try:
   normalized_locale = locale.getlocale()
  except ValueError:
   (yield new_locale)
  else:
   if all(((lc is not None) for lc in normalized_locale)):
    (yield '.'.join(normalized_locale))
   else:
    (yield new_locale)
 finally:
  locale.setlocale(lc_var, current_locale)

@ contextmanager def set_locale ( new_locale , lc_var = locale . LC_ALL ) : current_locale = locale . getlocale ( ) try : locale . setlocale ( lc_var , new_locale ) try : normalized_locale = locale . getlocale ( ) except ValueError : ( yield new_locale ) else : if all ( ( ( lc is not None ) for lc in normalized_locale ) ) : ( yield '.' . join ( normalized_locale ) ) else : ( yield new_locale ) finally : locale . setlocale ( lc_var , current_locale )
retrieve locale from a prioritized list of sources and then set locale and save it cls: self object force: a locale to force set return: locale as string or none if i18n should be disabled .