Skip to content

mypy reporting error with default value for typevar #8739

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
zanieb opened this issue Apr 28, 2020 · 2 comments
Closed

mypy reporting error with default value for typevar #8739

zanieb opened this issue Apr 28, 2020 · 2 comments

Comments

@zanieb
Copy link

zanieb commented Apr 28, 2020

I’m struggling with a generic type var and have reduced it to a simple example. I’m trying to have a function that takes a generic type and returns an instance of that type

from __future__ import annotations

from typing import Type, TypeVar


class A:
    pass

class B(A):
    pass

T = TypeVar('T', bound=A)

def test(x: Type[T] = B) -> T:
    return x()
test.py:14: error: Incompatible default for argument "x" (default has type "Type[B]", argument has type "Type[T]")

Am I missing something obvious or is this a bug? My understanding is that Type[B] should be a subset of Type[T] and not cause an incompatibility

I get a similar error with modifications such as

T = TypeVar('T', bound=B)

and

def test(x: Type[T] = A) -> T:
    return x()

I made a thread on gitter and got no response 🤷

Versions
mypy 0.770
Python 3.8.2

@hauntsaninja
Copy link
Collaborator

You get a similar failure on a simpler, more general case:

from typing import *

T = TypeVar("T")

def foo(x: T = 0) -> T: ...

reveal_type(foo())

So it looks like this is a duplicate of #3737. As that thread mentions, a good workaround is using overload.

@zanieb
Copy link
Author

zanieb commented Apr 29, 2020

Ah geez, I did not see that. I'll try the solutions there and close this.

Thanks!

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