[docs] [issue27402] Sequence example in typing module documentation does not typecheck

Michael Lee report at bugs.python.org
Mon Jun 27 13:09:40 EDT 2016

New submission from Michael Lee:

In the documentation for the `typing` module, the [entry for the `List` type][0] uses the following example to help demonstrate when to use `Sequence` vs `List`:

    T = TypeVar('T', int, float)

    def vec2(x: T, y: T) -> List[T]:
        return [x, y]

    def slice__to_4(vector: Sequence[T]) -> List[T]:
        return vector[0:4]

However, the `slice__to_4` function does not actually typecheck since there's no guarantee that a slice of a sequence will return a `List`. For example the vector could be a numpy array or a custom subclass of `collections.abc.Sequence` with an unusual `__getitem__`. (Mypy correctly catches this error and complains about an "Incompatible return value type").

The documentation should probably be updated to use an example that _does_ typecheck, though I'm not sure what exactly that example might look like? Maybe replace `slice__to_4` with something like this?

    def keep_positives(vector: Sequence[T]) -> List[T]:
        return [item for item in vector if item > 0]

assignee: docs at python
components: Documentation
messages: 269389
nosy: docs at python, michael0x2a
priority: normal
severity: normal
status: open
title: Sequence example in typing module documentation does not typecheck
versions: Python 3.5, Python 3.6

Python tracker <report at bugs.python.org>

More information about the docs mailing list