Developers can use type hints to specify which type a function is expected to return. Doing so improves maintainability since it clarifies the
contract of the function, making it easier to use and understand.
When annotating a function with a specific type hint, it is expected that the returned value matches the type specified in the hint.
If the type hint specifies a class or a named type, then the value returned should be an instance of that class or type. If the type hint specifies
a structural type, then the value returned should have the same structure as the type hint.
In the following example, while Bucket
does not directly inherit from Iterable
, it does implement the
Iterable
protocol thanks to its __iter__
method and can therefore be used as a valid Iterable
return type.
from collections.abc import Iterator, Iterable
class Bucket: # Note: no base classes
...
def __len__(self) -> int: ...
def __iter__(self) -> Iterator[int]: ...
def collect() -> Iterable: return Bucket()
Since type annotations are not enforced at runtime, returning a completely different type might not fail. It is however likely to be unintended and
will lead to maintainability issues, if not bugs.