Skip to content

Recursive sequence type of Sequence[NotAString] should not accept str #819

@jorenham

Description

@jorenham

This is a (p)repost from python/mypy#18184, which also applies here:

The false negative can be reproduced with:

from collections.abc import Sequence
from typing import TypeAlias

class Scalar: ...

Vector: TypeAlias = Sequence[Scalar]
Tensor: TypeAlias = Vector | Sequence["Tensor"]

accepted_vector: Vector = [Scalar()]     # true negative
rejected_vector: Vector = "duck"         # true positive: ducks aren't vectors

accepted_tensor: Tensor = [[[Scalar()]]] # true negative
rejected_tensor1: Tensor = object()      # true positive: objects aren't tensors
rejected_tensor2: Tensor = "duck"        # false negative: ducks are tensors...?

mypy-play


alternative example:

class Increment[T]:  # covariant
    def current(self, /) -> T: ...  # type: ignore[empty-body]

type Infinity = Increment[Infinity]

type Zero = Increment[None]
type Integer = Zero | Increment[Integer]


def int2inf(integer: Integer, /) -> Infinity:
    return integer  # rejected => ok

def inf2int(infinity: Infinity, /) -> Integer:
    return infinity  # accepted => wut

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions