Skip to content

Overriding generic method in subclass of concretized generic #2886

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

Closed
miedzinski opened this issue Feb 20, 2017 · 2 comments
Closed

Overriding generic method in subclass of concretized generic #2886

miedzinski opened this issue Feb 20, 2017 · 2 comments

Comments

@miedzinski
Copy link
Contributor

from typing import Generic, TypeVar
T = TypeVar('T')
class A(Generic[T]):
    def f(self, x: T) -> T:
        return x
class B(A[int]):  # leave signature as is
    def f(self, x: T) -> T:
        return x
class C(A[int]):  # concretize
    def f(self, x: int) -> int:
        return x
class D(A[int]):  # incorrectly override
    def f(self, x: str) -> str:
        return x

Currently mypy reports an error only in class D, but it should complain about B as well, because

  1. It is not generic, but we are somehow allowed to use T. Does it come from Allow omitting redundant Generic[T] in base classes #2811?
  2. I believe it violates LSP, just like D.
@ilevkivskyi
Copy link
Member

First, methods are actually functions, and therefore are always allowed to be generic, and this has nothing to do with #2811
Second, mypy is not super strong at callable subtyping now, but in this particular case I think everything is right. At least I didn't find any situation with A[int] and B defined this way that is not caught by mypy but fails at runtime.

@JukkaL
Copy link
Collaborator

JukkaL commented Feb 21, 2017

I agree that mypy is correct -- the method B.f is generic (even though B is not generic) and it can be made to have the base class signature by substituting T with int. B.f can be called with an arbitrary argument type, but it's okay for a subclass to a have a more general signature than the base class.

@JukkaL JukkaL closed this as completed Feb 21, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants