Skip to content

Commit 1ffc672

Browse files
[3.10] gh-99535: Add test for inheritance of annotations and update documentation (GH-99990) (#100509)
(cherry picked from commit f5b7b19) Co-authored-by: MonadChains <monadchains@gmail.com>
1 parent bb159b4 commit 1ffc672

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
@@ -2233,6 +2233,10 @@ Introspection helpers
22332233
.. versionchanged:: 3.9
22342234
Added ``include_extras`` parameter as part of :pep:`593`.
22352235

2236+
.. versionchanged:: 3.10
2237+
Calling ``get_type_hints()`` on a class no longer returns the annotations
2238+
of its base classes.
2239+
22362240
.. function:: get_args(tp)
22372241
.. function:: get_origin(tp)
22382242

Lib/test/test_grammar.py

+22
Original file line numberDiff line numberDiff line change
@@ -406,6 +406,28 @@ class Cbad2(C):
406406
x: int
407407
x.y: list = []
408408

409+
def test_annotations_inheritance(self):
410+
# Check that annotations are not inherited by derived classes
411+
class A:
412+
attr: int
413+
class B(A):
414+
pass
415+
class C(A):
416+
attr: str
417+
class D:
418+
attr2: int
419+
class E(A, D):
420+
pass
421+
class F(C, A):
422+
pass
423+
self.assertEqual(A.__annotations__, {"attr": int})
424+
self.assertEqual(B.__annotations__, {})
425+
self.assertEqual(C.__annotations__, {"attr" : str})
426+
self.assertEqual(D.__annotations__, {"attr2" : int})
427+
self.assertEqual(E.__annotations__, {})
428+
self.assertEqual(F.__annotations__, {})
429+
430+
409431
def test_var_annot_metaclass_semantics(self):
410432
class CMeta(type):
411433
@classmethod

0 commit comments

Comments
 (0)