python / python/cpython

Cyclic reference lead to contextlib.contextmanager exception not being deleted

Open
#129,280 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

stdlib type-bug
Dominant language
Python
Stars
77.2k
Forks
35.9k
PR merge metrics
PR metrics pending

Description

Bug report

Bug description:

Consider the following code.

from contextlib import contextmanager

class MyException(Exception):
	def __del__(self):
		print("deleted")

@contextmanager
def f():
	try:
		yield
	except MyException:
		pass

with f():
	raise MyException()

print("done")

In Python 3.11 the printed value is deleted done, in Python 3.12 the printed value is done deleted. Which means the exception is kept around much longer than it need to be, this is caused by a reference cycle between the exception and the frame in contextmanager implementation.

CPython versions tested on:

3.11, 3.12

Operating systems tested on:

Linux

Linked PRs
  • gh-129276

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the supplied contextlib.contextmanager example on Python 3.11 and 3.12, then inspect the contextlib.contextmanager implementation to trace the exception and frame references. Done means the exception is released without the delayed deletion observed in Python 3.12; linked PR gh-129276 indicates work is already underway.

Written by the indexing model from the issue text.

Assessment

Tech stack
python
Domain
backend
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.