Skip to content

Add clarification for overloading example #3369

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 11, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 24 additions & 1 deletion docs/source/function_overloading.rst
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ accurately describe the function's behavior.
# It may or may not have type hints; if it does,
# these are checked against the overload definitions
# as well as against the implementation body.
def __getitem__(self, index):
def __getitem__(self, index: Union[int, slice]) -> Union[T, Sequence[T]]:
# This is exactly the same as before.
if isinstance(index, int):
... # Return a T here
Expand All @@ -65,6 +65,29 @@ accurately describe the function's behavior.
else:
raise TypeError(...)

Calls to overloaded functions are type checked against the variants,
not against the implementation. A call like ``my_list[5]`` would have
type ``T``, not ``Union[T, Sequence[T]]`` because it matches the
first overloaded definition, and ignores the type annotations on the
implementation of ``__getitem__``. The code in the body of the
definition of ``__getitem__`` is checked against the annotations on
the the corresponding declaration. In this case the body is checked
with ``index: Union[int, slice]`` and a return type
``Union[T, Sequence[T]]``. If there are no annotations on the
corresponding definition, then code in the function body is not type
checked.

The annotations on the function body must be compatible with the
types given for the overloaded variants listed above it. The type
checker will verify that all the types listed the overloaded variants
are compatible with the types given for the implementation. In this
case it checks that the parameter type ``int`` and the return type
``T`` are compatible with ``Union[int, slice]`` and
``Union[T, Sequence[T]]`` for the first variant. For the second
variant it verifies that the parameter type ``slice`` are the return
type ``Sequence[T]`` are compatible with ``Union[int, slice]`` and
``Union[T, Sequence[T]]``.

Overloaded function variants are still ordinary Python functions and
they still define a single runtime object. There is no automatic
dispatch happening, and you must manually handle the different types
Expand Down