]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.10] gh-99535: Add test for inheritance of annotations and update documentation...
authorJelle Zijlstra <jelle.zijlstra@gmail.com>
Tue, 27 Dec 2022 04:44:53 +0000 (20:44 -0800)
committerGitHub <noreply@github.com>
Tue, 27 Dec 2022 04:44:53 +0000 (20:44 -0800)
(cherry picked from commit f5b7b19bf10724d831285fb04e00f763838bd555)

Co-authored-by: MonadChains <monadchains@gmail.com>
Doc/howto/annotations.rst
Doc/library/typing.rst
Lib/test/test_grammar.py

index 2bc2f2d4c839e2df8d7ae31e4dc95c0923f6e3cd..472069032d6509c432892613d8b405d150ed6866 100644 (file)
@@ -57,6 +57,12 @@ Accessing The Annotations Dict Of An Object In Python 3.10 And Newer
   newer is to call :func:`getattr` with three arguments,
   for example ``getattr(o, '__annotations__', None)``.
 
+  Before Python 3.10, accessing ``__annotations__`` on a class that
+  defines no annotations but that has a parent class with
+  annotations would return the parent's ``__annotations__``.
+  In Python 3.10 and newer, the child class's annotations
+  will be an empty dict instead.
+
 
 Accessing The Annotations Dict Of An Object In Python 3.9 And Older
 ===================================================================
index d415f149027f195384e52ef4223060969712771d..d3275209e938e8d46b11fcde989d966b312cb534 100644 (file)
@@ -2233,6 +2233,10 @@ Introspection helpers
    .. versionchanged:: 3.9
       Added ``include_extras`` parameter as part of :pep:`593`.
 
+   .. versionchanged:: 3.10
+      Calling ``get_type_hints()`` on a class no longer returns the annotations
+      of its base classes.
+
 .. function:: get_args(tp)
 .. function:: get_origin(tp)
 
index 2b9f7df0bd25d1a817f9b0796d3acf7554148b8a..27b14ab836b6cd12c1a19bb125e6d27a0138e6ff 100644 (file)
@@ -406,6 +406,28 @@ class GrammarTests(unittest.TestCase):
                 x: int
                 x.y: list = []
 
+    def test_annotations_inheritance(self):
+        # Check that annotations are not inherited by derived classes
+        class A:
+            attr: int
+        class B(A):
+            pass
+        class C(A):
+            attr: str
+        class D:
+            attr2: int
+        class E(A, D):
+            pass
+        class F(C, A):
+            pass
+        self.assertEqual(A.__annotations__, {"attr": int})
+        self.assertEqual(B.__annotations__, {})
+        self.assertEqual(C.__annotations__, {"attr" : str})
+        self.assertEqual(D.__annotations__, {"attr2" : int})
+        self.assertEqual(E.__annotations__, {})
+        self.assertEqual(F.__annotations__, {})
+
+
     def test_var_annot_metaclass_semantics(self):
         class CMeta(type):
             @classmethod