Skip to content

Commit f5b7b19

Browse files
authored
gh-99535: Add test for inheritance of annotations and update documentation (#99990)
1 parent e4b43eb commit f5b7b19

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed

Doc/howto/annotations.rst

+6
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,12 @@ Accessing The Annotations Dict Of An Object In Python 3.10 And Newer
5757
newer is to call :func:`getattr` with three arguments,
5858
for example ``getattr(o, '__annotations__', None)``.
5959

60+
Before Python 3.10, accessing ``__annotations__`` on a class that
61+
defines no annotations but that has a parent class with
62+
annotations would return the parent's ``__annotations__``.
63+
In Python 3.10 and newer, the child class's annotations
64+
will be an empty dict instead.
65+
6066

6167
Accessing The Annotations Dict Of An Object In Python 3.9 And Older
6268
===================================================================

Doc/library/typing.rst

+4
Original file line numberDiff line numberDiff line change
@@ -2777,6 +2777,10 @@ Introspection helpers
27772777
.. versionchanged:: 3.9
27782778
Added ``include_extras`` parameter as part of :pep:`593`.
27792779

2780+
.. versionchanged:: 3.10
2781+
Calling ``get_type_hints()`` on a class no longer returns the annotations
2782+
of its base classes.
2783+
27802784
.. versionchanged:: 3.11
27812785
Previously, ``Optional[t]`` was added for function and method annotations
27822786
if a default value equal to ``None`` was set.

Lib/test/test_grammar.py

+22
Original file line numberDiff line numberDiff line change
@@ -415,6 +415,28 @@ class Cbad2(C):
415415
x: int
416416
x.y: list = []
417417

418+
def test_annotations_inheritance(self):
419+
# Check that annotations are not inherited by derived classes
420+
class A:
421+
attr: int
422+
class B(A):
423+
pass
424+
class C(A):
425+
attr: str
426+
class D:
427+
attr2: int
428+
class E(A, D):
429+
pass
430+
class F(C, A):
431+
pass
432+
self.assertEqual(A.__annotations__, {"attr": int})
433+
self.assertEqual(B.__annotations__, {})
434+
self.assertEqual(C.__annotations__, {"attr" : str})
435+
self.assertEqual(D.__annotations__, {"attr2" : int})
436+
self.assertEqual(E.__annotations__, {})
437+
self.assertEqual(F.__annotations__, {})
438+
439+
418440
def test_var_annot_metaclass_semantics(self):
419441
class CMeta(type):
420442
@classmethod

0 commit comments

Comments
 (0)