Skip to content

GH-141148: Ensure decimal.getcontext() returns fresh copy.#151953

Draft
nascheme wants to merge 2 commits into
python:mainfrom
nascheme:decimal_ctx_depth
Draft

GH-141148: Ensure decimal.getcontext() returns fresh copy.#151953
nascheme wants to merge 2 commits into
python:mainfrom
nascheme:decimal_ctx_depth

Conversation

@nascheme

@nascheme nascheme commented Jun 22, 2026

Copy link
Copy Markdown
Member

We need a per-task copy of decimal.Context() so that mutations are isolated between asyncio tasks and threads using
sys.flags.thread_inherit_context. This is done by adding a "depth" counter to PyContext and copying the decimal.Context() instance whenever it doesn't match the depth of the current PyContext.

This is an alternative to GH-146482. It has the following differences:

  • it avoids the potential problem of keeping context vars alive longer, via the ctx_vars_origin reference. Instead, we are just using a counter here to track depth.
  • it avoids copying decimal.Context in the case that the context is reused many times, e.g. for asyncio tasks
  • it creates a bit more work for the _pydecimal and _decimal.c code since it has to track the depth on it's Context instance

We need a per-task copy of decimal.Context() so that mutations are
isolated between asyncio tasks and threads using
sys.flags.thread_inherit_context.  This is done by adding a "depth"
counter to PyContext and copying the decimal.Context() instance whenever
it doesn't match the depth of the current PyContext.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant