Skip to content

Use of covariant type arguments in methods needs to be reported as error #3139

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
pkch opened this issue Apr 7, 2017 · 2 comments
Closed

Comments

@pkch
Copy link
Contributor

pkch commented Apr 7, 2017

Contravariant type args in method return is correctly identified as type errors; but covariant type args in method arguments does not create an error:

T_co = TypeVar('T_co', covariant=True)

class Covariant(Generic[T_co]):
    def f(x: T_co) -> T_co:  # Need an error here
        return x

T_contra = TypeVar('T_contra', contravariant=True)

class Contravariant(Generic[T_contra]):
    def f(x: T_contra) -> T_contra:  # E: Cannot use a contravariant type variable as return type
        return x

It works correctly for normal functions though (not methods).

@ilevkivskyi
Copy link
Member

This is because x in your example is interpreted as self. The self in methods is indeed special (it actually varies covariantly in some sense). If I change your example as following:

class Covariant(Generic[T_co]):
    def f(self, x: T_co) -> T_co:  # Note 'self' added
        return x

Then mypy correctly gives an error:

error: Cannot use a covariant type variable as a parameter

For variance of self-types we have issue #2352

@pkch
Copy link
Contributor Author

pkch commented Apr 7, 2017

Ah I didn't mean self-types, I just wrote the signature incorrectly 😛

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

2 participants