Skip to content
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

Regression: IO[str] not compatible with SupportsWrite[AnyStr] #17863

Closed
JukkaL opened this issue Oct 2, 2024 · 2 comments · Fixed by #17873
Closed

Regression: IO[str] not compatible with SupportsWrite[AnyStr] #17863

JukkaL opened this issue Oct 2, 2024 · 2 comments · Fixed by #17873
Assignees
Labels
bug mypy got something wrong false-positive mypy gave an error on correct code topic-protocols topic-type-variables

Comments

@JukkaL
Copy link
Collaborator

JukkaL commented Oct 2, 2024

This code generates a false positive, but type checked cleanly on mypy 1.11:

from typing import IO
from shutil import copyfileobj

f: IO[str]
copyfileobj(f, f)  # Cannot infer type argument 1 of "copyfileobj"

I believe the reason is that the definition of IO.write changed in typeshed, and this triggered a mypy bug. Here's how IO.write is currently defined:

class IO(Iterator[AnyStr]):
    ...
    @abstractmethod
    @overload
    def write(self: IO[bytes], s: ReadableBuffer, /) -> int: ...
    @abstractmethod
    @overload
    def write(self, s: AnyStr, /) -> int: ...
@JukkaL JukkaL added bug mypy got something wrong topic-type-variables topic-protocols false-positive mypy gave an error on correct code labels Oct 2, 2024
@JukkaL JukkaL self-assigned this Oct 2, 2024
@JukkaL
Copy link
Collaborator Author

JukkaL commented Oct 2, 2024

Self-contained test case:

from typing import TypeVar, Generic, Protocol, overload

T_contra = TypeVar("T_contra", contravariant=True)
AnyStr = TypeVar("AnyStr", str, bytes)

class SupportsWrite(Protocol[T_contra]):
    def write(self, s: T_contra, /) -> None: ...

class Buffer: ...

class IO(Generic[AnyStr]):
    @overload
    def write(self: IO[bytes], s: Buffer, /) -> None: ...
    @overload
    def write(self, s: AnyStr, /) -> None: ...
    def write(self, s): ...

def foo(fdst: SupportsWrite[AnyStr]) -> None: ...

x: IO[str]
foo(x)  # Value of type variable "AnyStr" of "foo" cannot be "Buffer"

It looks like we are picking up constraints from the wrong overload item.

@hauntsaninja
Copy link
Collaborator

Related: #15031

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong false-positive mypy gave an error on correct code topic-protocols topic-type-variables
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants