-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
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
Cannot cast value to TypeVar #6440
Comments
Here is a more minimal repro: from typing import TypeVar, Callable, cast
T = TypeVar('T')
def foo(x: Callable[[], T] = lambda: cast(T, 0)) -> T:
return x() This seems inconsistent because this passes type checking: from typing import TypeVar, Callable, cast, Optional
T = TypeVar('T')
def foo(x: Optional[Callable[[], T]] = None) -> T:
if x is None:
x = lambda: cast(T, 0)
return x() I'm not sure why the difference in scopes would explain one type checking and the other not... |
Troubles with specifying defaults for generic arguments is a known issue #3737. And the fact that the cast doesn't work there is unfortunate. A typical workaround is to use an overload. In your case it will actually make the signature more correct: @overload
def group_by(items: Iterable[T], *, key: Callable[[T], Tk]) -> Mapping[Tk, List[T]]: ...
@overload
def group_by(items: Iterable[T], *,
key: Callable[[T], Tk], value: Callable[[T], Tv]) -> Mapping[Tk, List[Tv]]: ... With your signature it is not possible to infer |
Closing as a duplicate of #3737 |
This is a bug report however it could be that I'm doing it wrong™. This is for mypy version 0.670
Consider this method:
Notice that the default parameter for
value
is an identity callable that castsx
toTv
. This produces an error:If I remove the call to
cast
, I get a different error which makes sense to me and was the original reason I addedcast
in the first place:Given that this method is mostly
TypeVar
based, what do you think would be the right behavior? I find the second error acceptable (becauseT
!=Tv
) but I findTv
not being a type very confusing and therefor a bug.The text was updated successfully, but these errors were encountered: