Return a context manager for a copy of the supplied context Uses a copy of the current context if no context is specified The returned context manager creates a local decimal context in a with statement: def sin(x): with localcontext() as ctx:
(ctx=None, **kwargs)
| 469 | del contextvars # Don't contaminate the namespace |
| 470 | |
| 471 | def localcontext(ctx=None, **kwargs): |
| 472 | """Return a context manager for a copy of the supplied context |
| 473 | |
| 474 | Uses a copy of the current context if no context is specified |
| 475 | The returned context manager creates a local decimal context |
| 476 | in a with statement: |
| 477 | def sin(x): |
| 478 | with localcontext() as ctx: |
| 479 | ctx.prec += 2 |
| 480 | # Rest of sin calculation algorithm |
| 481 | # uses a precision 2 greater than normal |
| 482 | return +s # Convert result to normal precision |
| 483 | |
| 484 | def sin(x): |
| 485 | with localcontext(ExtendedContext): |
| 486 | # Rest of sin calculation algorithm |
| 487 | # uses the Extended Context from the |
| 488 | # General Decimal Arithmetic Specification |
| 489 | return +s # Convert result to normal context |
| 490 | |
| 491 | >>> setcontext(DefaultContext) |
| 492 | >>> print(getcontext().prec) |
| 493 | 28 |
| 494 | >>> with localcontext(): |
| 495 | ... ctx = getcontext() |
| 496 | ... ctx.prec += 2 |
| 497 | ... print(ctx.prec) |
| 498 | ... |
| 499 | 30 |
| 500 | >>> with localcontext(ExtendedContext): |
| 501 | ... print(getcontext().prec) |
| 502 | ... |
| 503 | 9 |
| 504 | >>> print(getcontext().prec) |
| 505 | 28 |
| 506 | """ |
| 507 | if ctx is None: |
| 508 | ctx = getcontext() |
| 509 | ctx_manager = _ContextManager(ctx) |
| 510 | for key, value in kwargs.items(): |
| 511 | if key not in _context_attributes: |
| 512 | raise TypeError(f"'{key}' is an invalid keyword argument for this function") |
| 513 | setattr(ctx_manager.new_context, key, value) |
| 514 | return ctx_manager |
| 515 | |
| 516 | |
| 517 | ##### Decimal class ####################################################### |
nothing calls this directly
no test coverage detected