Python十进制自定义上下文

时间:2016-02-16 15:45:09

标签: python decimal contextmanager

在另一个上下文中使用时,上下文管理器decimal.localcontext显然会被忽略。以下示例说明了这一点(Python 2.7):

from decimal import Decimal, Context, localcontext
from contextlib import contextmanager

@contextmanager
def precision_context(precision):
    yield localcontext(Context(prec=precision))

PRECISION=4
SMALL_NUMBER=Decimal('0.0001')

with localcontext(Context(prec=PRECISION)):
    # This is working as it should
    print SMALL_NUMBER + 1 # prints 1.000

with precision_context(PRECISION):
    # But this is not
    print SMALL_NUMBER + 1 # prints 1.0001

为什么会这样,以及如何解决?

1 个答案:

答案 0 :(得分:3)

这是因为您实际上没有进入上下文管理器(调用__enter__方法)。没有什么叫localcontext(Context(prec=precision)).__enter__,因为

with precision_context(PRECISION):

仅输入precision_context上下文管理器。

您可以通过添加另一个with语句来解决问题:

with precision_context(PRECISION) as ctx:
    # Enter `localcontext(Context(prec=precision))`
    with ctx:
        print(SMALL_NUMBER + 1) # prints 1.000