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.p
(ctx=None, **kwargs)
| 377 | del contextvars # Don't contaminate the namespace |
| 378 | |
| 379 | def localcontext(ctx=None, **kwargs): |
| 380 | """Return a context manager for a copy of the supplied context |
| 381 | |
| 382 | Uses a copy of the current context if no context is specified |
| 383 | The returned context manager creates a local decimal context |
| 384 | in a with statement: |
| 385 | def sin(x): |
| 386 | with localcontext() as ctx: |
| 387 | ctx.prec += 2 |
| 388 | # Rest of sin calculation algorithm |
| 389 | # uses a precision 2 greater than normal |
| 390 | return +s # Convert result to normal precision |
| 391 | |
| 392 | def sin(x): |
| 393 | with localcontext(ExtendedContext): |
| 394 | # Rest of sin calculation algorithm |
| 395 | # uses the Extended Context from the |
| 396 | # General Decimal Arithmetic Specification |
| 397 | return +s # Convert result to normal context |
| 398 | |
| 399 | >>> setcontext(DefaultContext) |
| 400 | >>> print(getcontext().prec) |
| 401 | 28 |
| 402 | >>> with localcontext(): |
| 403 | ... ctx = getcontext() |
| 404 | ... ctx.prec += 2 |
| 405 | ... print(ctx.prec) |
| 406 | ... |
| 407 | 30 |
| 408 | >>> with localcontext(ExtendedContext): |
| 409 | ... print(getcontext().prec) |
| 410 | ... |
| 411 | 9 |
| 412 | >>> print(getcontext().prec) |
| 413 | 28 |
| 414 | """ |
| 415 | if ctx is None: |
| 416 | ctx = getcontext() |
| 417 | ctx_manager = _ContextManager(ctx) |
| 418 | for key, value in kwargs.items(): |
| 419 | if key not in _context_attributes: |
| 420 | raise TypeError(f"'{key}' is an invalid keyword argument for this function") |
| 421 | setattr(ctx_manager.new_context, key, value) |
| 422 | return ctx_manager |
| 423 | |
| 424 | |
| 425 | def IEEEContext(bits, /): |
searching dependent graphs…