Possible to specify generic typed class via its __init__()? #1084
Answered
by
BvB93
abelcheung
asked this question in
Q&A
-
I'd want to write a stub for some external class (not controlled by me), where some of its method may return different type depending on how it is constructed. For example: _T = TypeVar('_T', str, int)
class Klass(Generic[_T]):
def __init__(self, is_int: bool) -> None: ...
def common_method(self) -> bool: ...
def do_it(self) -> list[_T]
x = Klass(True) # x expected to be Klass[int]
y = Klass(False) # y expected to be Klass[str]
x.do_it() # expects list[int]
y.do_it() # expects list[str] Is such maneuvering possible without forcefully annotating |
Beta Was this translation helpful? Give feedback.
Answered by
BvB93
Feb 19, 2022
Replies: 1 comment 2 replies
-
An option here would be to overload class Klass(Generic[_T]):
@overload
def __init__(self: Klass[int], is_int: Literal[True]) -> None: ...
@overload
def __init__(self: Klass[str], is_int: Literal[False]) -> None: ... |
Beta Was this translation helpful? Give feedback.
2 replies
Answer selected by
abelcheung
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
An option here would be to overload
__init__
w.r.t. boolean literals: