-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
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
How to type result based on constructor parameters? #10207
Comments
This isn't something you can do with mypy. Mypy is a static type checker. The type you want to describe is inherently dynamic. It depends on the value of a attribute/parameter at runtime. Mypy can only check types with are known at "compile time". |
I do believe @vnmabus's example should work; Literal types are part of the type system now. Maybe we don't handle them properly in overload resolution though. Here's a self-contained example:
The call to |
Here's a solution that works in pyright and almost works in mypy. I'm not sure why, but mypy appears to choose the wrong from typing import Generic, Literal, Tuple, TypeVar, Union, overload
T = TypeVar("T", bound=bool)
class A(Generic[T]):
@overload
def __init__(self: A[Literal[False]], return_tuple: Literal[False] = ...) -> None:
...
@overload
def __init__(self: A[Literal[True]], return_tuple: Literal[True]) -> None:
...
def __init__(self, return_tuple: bool = False) -> None:
self.return_tuple = return_tuple
@overload
def __call__(self: A[Literal[True]]) -> Tuple[int, int]:
...
@overload
def __call__(self: A[Literal[False]]) -> int:
...
def __call__(self) -> Union[int, Tuple[int, int]]:
if self.return_tuple:
return (1, 2)
return 1
a1 = A(return_tuple=True)
reveal_type(a1)
reveal_type(a1()) # Tuple[int, int]
a2 = A()
reveal_type(a2)
reveal_type(a2()) # int |
I am trying to type code like this:
I have tried to make
A
generic and use overloads on the self parameter in several ways but none seems to work:where
T
is eitheror
The first case mark errors in the definition of the
TypeVar
, theGeneric
and the optional parameter in__init__
. The second one marks an error only in the optional parameter (even if it is essentially the same type).reveal_type
does not have the expected result in both cases.Am I doing something wrong or is this case just not currently taken into consideration?
The text was updated successfully, but these errors were encountered: