@@ -56,7 +56,7 @@ accurately describe the function's behavior.
56
56
# It may or may not have type hints; if it does,
57
57
# these are checked against the overload definitions
58
58
# as well as against the implementation body.
59
- def __getitem__ (self , index ) :
59
+ def __getitem__ (self , index : Union[ int , slice ]) -> Union[T, Sequence[T]] :
60
60
# This is exactly the same as before.
61
61
if isinstance (index, int ):
62
62
... # Return a T here
@@ -65,6 +65,29 @@ accurately describe the function's behavior.
65
65
else :
66
66
raise TypeError (... )
67
67
68
+ Calls to overloaded functions are type checked against the variants,
69
+ not against the implementation. A call like ``my_list[5] `` would have
70
+ type ``T ``, not ``Union[T, Sequence[T]] `` because it matches the
71
+ first overloaded definition, and ignores the type annotations on the
72
+ implementation of ``__getitem__ ``. The code in the body of the
73
+ definition of ``__getitem__ `` is checked against the annotations on
74
+ the the corresponding declaration. In this case the body is checked
75
+ with ``index: Union[int, slice] `` and a return type
76
+ ``Union[T, Sequence[T]] ``. If there are no annotations on the
77
+ corresponding definition, then code in the function body is not type
78
+ checked.
79
+
80
+ The annotations on the function body must be compatible with the
81
+ types given for the overloaded variants listed above it. The type
82
+ checker will verify that all the types listed the overloaded variants
83
+ are compatible with the types given for the implementation. In this
84
+ case it checks that the parameter type ``int `` and the return type
85
+ ``T `` are compatible with ``Union[int, slice] `` and
86
+ ``Union[T, Sequence[T]] `` for the first variant. For the second
87
+ variant it verifies that the parameter type ``slice `` are the return
88
+ type ``Sequence[T] `` are compatible with ``Union[int, slice] `` and
89
+ ``Union[T, Sequence[T]] ``.
90
+
68
91
Overloaded function variants are still ordinary Python functions and
69
92
they still define a single runtime object. There is no automatic
70
93
dispatch happening, and you must manually handle the different types
0 commit comments