Skip to content

gh-135552: Add tests that check if weakref for tp_subclasses cleared after finalization #136304

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 11 commits into
base: main
Choose a base branch
from

Conversation

sergey-miryanov
Copy link
Contributor

@sergey-miryanov sergey-miryanov commented Jul 4, 2025

@sergey-miryanov
Copy link
Contributor Author

I believe this PR should skip news

@nascheme
Copy link
Member

nascheme commented Jul 8, 2025

This looks okay to me. Some suggested improvements. The new test might fit better into test_weakref.py but that's minor.

I don't think it's required to run these in a separate Python process. That makes the test run slower and it's not supposed to crash. Generally a separate process is used for the tests that exercise the interpreter shutdown logic and we are not testing that. So you could just do:

    def test_clearing_weakrefs_in_gc(self):
        # This test checks that:
        # 1. weakrefs for types with callbacks are cleared before the
        # finalizer is called
        # 2. weakrefs for types without callbacks are cleared after the
        # finalizer is called
        # 3. other weakrefs cleared before the finalizer is called
        errors = []
        class Class:
            def __init__(self):
                self._self = self
                self._1 = weakref.ref(Class, lambda x: None)
                self._2 = weakref.ref(Class)
                self._3 = weakref.ref(self)

            def __del__(self):
                if self._1() is not None:
                    errors.append("Type weakref with callback is not None as expected")
                if self._2() is not Class:
                    errors.append("Type weakref is not Class as expected")
                if self._3() is not None:
                    errors.append("Instance weakref is not None as expected")
        Class()
        gc.collect()
        self.assertEqual(errors, [])

I find the variable naming a bit esoteric. I would have just called them wr1, wr2 and wr3.

@sergey-miryanov
Copy link
Contributor Author

@nascheme Thanks for review! Fixed.

@sergey-miryanov
Copy link
Contributor Author

@kumaraditya303 Thanks for review!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
awaiting review skip news tests Tests in the Lib/test dir
Projects
None yet
Development

Successfully merging this pull request may close these issues.

6 participants