當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Python decimal.localcontext用法及代碼示例

用法:

decimal.localcontext(ctx=None)

返回一個上下文管理器,它將在進入with-statement 時將活動線程的當前上下文設置為ctx 的副本,並在退出with-statement 時恢複先前的上下文。如果未指定上下文,則使用當前上下文的副本。

例如,以下代碼將當前小數精度設置為 42 位,執行計算,然後自動恢複之前的上下文:

from decimal import localcontext

with localcontext() as ctx:
    ctx.prec = 42   # Perform a high precision calculation
    s = calculate_something()
s = +s  # Round the final result back to the default precision

相關用法


注:本文由純淨天空篩選整理自python.org大神的英文原創作品 decimal.localcontext。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。