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

Type checking problem with generic __init__() of generic class. #7369

Open
Luffbee opened this issue Feb 29, 2024 · 0 comments
Open

Type checking problem with generic __init__() of generic class. #7369

Luffbee opened this issue Feb 29, 2024 · 0 comments
Labels
bug Something isn't working

Comments

@Luffbee
Copy link

Luffbee commented Feb 29, 2024

Describe the bug
I'm trying to write a generic container class Container[T], and support method do_map(self, func: Callable[[T], W]) -> Container[W] that do a transform like map().
For some reasons, I want the the __init__ to accept a list[U] and a function Callable[[U], T], and call map() in the __init__.
Then the do_map() method just need to call the construction of the new container with type Container[W].
However, the following code (Container0) is rejected by pyright, but mypy accepts it.
Although I can bypass it by a helper function (Container1 with do_map_helper), it's not convenient, and seems like a bug.

Code or Screenshots

# container.py
from typing import Callable, Generic, TypeVar

T = TypeVar("T")
U = TypeVar("U")
W = TypeVar("W")


class Container0(Generic[T]):
    def __init__(self, vals: list[U], func: Callable[[U], T]):
        self._vals = list(map(func, vals))

    def do_map(self, func: Callable[[T], W]) -> "Container0[W]":
        return Container0(self._vals, func)


class Container1(Generic[T]):
    def __init__(self, vals: list[U], func: Callable[[U], T]):
        self._vals = list(map(func, vals))

    def do_map(self, func: Callable[[T], W]) -> "Container1[W]":
        return do_map_helper(self, func)


def do_map_helper(c: Container1[T], func: Callable[[T], W]) -> Container1[W]:
    return Container1(c._vals, func)

image
image

The type info of the Container0 in the do_map() function seems right, but the type check of argument and parameter report error:
image

If your code relies on symbols that are imported from a third-party library, include the associated import statements and specify which versions of those libraries you have installed.

VS Code extension or command-line
This problem can be reproduced by both Pylance and pyright command-line.

$ pyright --version; mypy --version
pyright 1.1.351
mypy 1.8.0 (compiled: yes)

image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant