Skip to content

Commit 783aaff

Browse files
tyehleddfisher
authored andcommitted
Add clarification for overloading example (#3369)
1 parent 3f5649a commit 783aaff

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

docs/source/function_overloading.rst

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ accurately describe the function's behavior.
5656
# It may or may not have type hints; if it does,
5757
# these are checked against the overload definitions
5858
# as well as against the implementation body.
59-
def __getitem__(self, index):
59+
def __getitem__(self, index: Union[int, slice]) -> Union[T, Sequence[T]]:
6060
# This is exactly the same as before.
6161
if isinstance(index, int):
6262
... # Return a T here
@@ -65,6 +65,29 @@ accurately describe the function's behavior.
6565
else:
6666
raise TypeError(...)
6767
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+
6891
Overloaded function variants are still ordinary Python functions and
6992
they still define a single runtime object. There is no automatic
7093
dispatch happening, and you must manually handle the different types

0 commit comments

Comments
 (0)