gh-132285: Fix that __annotate__ is not deleted when __annotations__ is deleted (#132286)

This commit is contained in:
sobolevn 2025-04-09 20:36:08 +03:00 committed by GitHub
parent 1f5682f3a2
commit 254110356d
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 23 additions and 2 deletions

View file

@ -57,6 +57,26 @@ class TypeAnnotationTests(unittest.TestCase):
del C.__annotations__
self.assertFalse("__annotations__" in C.__dict__)
def test_del_annotations_and_annotate(self):
# gh-132285
called = False
class A:
def __annotate__(format):
nonlocal called
called = True
return {'a': int}
self.assertEqual(A.__annotations__, {'a': int})
self.assertTrue(called)
self.assertTrue(A.__annotate__)
del A.__annotations__
called = False
self.assertEqual(A.__annotations__, {})
self.assertFalse(called)
self.assertIs(A.__annotate__, None)
def test_descriptor_still_works(self):
class C:
def __init__(self, name=None, bases=None, d=None):

View file

@ -0,0 +1,2 @@
Fix that :attr:`type.__annotate__` was not deleted, when
:attr:`type.__annotations__` was deleted.

View file

@ -2066,8 +2066,7 @@ type_set_annotations(PyObject *tp, PyObject *value, void *Py_UNUSED(closure))
if (result < 0) {
Py_DECREF(dict);
return -1;
}
else if (result == 0) {
} else { // result can be 0 or 1
if (PyDict_Pop(dict, &_Py_ID(__annotate__), NULL) < 0) {
PyType_Modified(type);
Py_DECREF(dict);