-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Default of TypeVar isn't respected for assignments. #18904
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
Comments
I think mypy is correct to reject this. The assignment class FooInterface(Interface):
@staticmethod
def foo() -> None: ...
class FooGeneric(MyGeneric[FooInterface]): ...
x = FooGeneric()
x._value.foo() # boom! |
Thank you. That's a good point. But in that case, how can I implement such a logic, that would force subclasses to obey type they declare? |
You might be interested in #3737 regarding the second example. It's not completely clear what you want from the first example so I can't offer a work around. But for the second you could try an overload and self-types I think? |
This is very similar to #3737 and #18812, the latter exactly about typevar
Do you need to provide any default implementation? I'd recommend going a level deeper and providing the default implementation that depends on from typing import Generic
from typing_extensions import TypeVar
class Interface: ...
_T = TypeVar("_T", bound=Interface, default=Interface)
class MyGeneric(Generic[_T]):
_value: type[_T]
class FooInterface(Interface):
foo: int
class FooGeneric(MyGeneric[FooInterface]):
def __init__(self) -> None:
super().__init__()
self._value = FooInterface |
Hello, here's an issue I stumbled upon.
In this example, I expect this code to be valid, because I have a default value for
_T
and don't have it in constructor.Also, while playing around I noticed that default doesn't work with default argument in
__init__
either.I'd expect this to be valid code because we define the default for the
Type[_T]
argument before the object is initialized, so it should fall back to thedefault
ofTypeVar
in that case. At least, that's what I would expect.Is this intended behavior?
The text was updated successfully, but these errors were encountered: