使用上下文管理器临时覆盖语言环境 [英] Temporarily override locale with a context manager

查看:71
本文介绍了使用上下文管理器临时覆盖语言环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有办法在代码块范围内临时激活语言环境?基本上,我想做这样的事情:

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_NUMERIC, 'nl_BE.utf8')

赞:

with override_locale(locale.LC_NUMERIC, 'nl_BE.utf8'):
   # Stuff here

这样,我还可以避免使用setlocale时可能出现的任何线程安全问题.我的用例是解析一个上传的文件,其中小数点使用逗号而不是句点作为小数点分隔符(例如,以1.25代替1.25).

That way I can also avoid any thread safety issues that may arise when using setlocale. My use case is parsing an uploaded file where the decimals use a comma instead of a period as the decimal separator (e.g. 1,25 instead of 1.25).

推荐答案

我发现 Babel 更适合我的用例:

I found out that Babel better fits my use case:

>>> parse_decimal('1,25', locale='nl_BE.utf8')
Decimal('1.25')

每当我需要解析荷兰语小数并且根本不需要覆盖任何语言环境时,这种方法就很有用.

This approach is useful whenever I need to parse a Dutch decimal and doesn't require overriding any locales at all.

这篇关于使用上下文管理器临时覆盖语言环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆