-
-
Notifications
You must be signed in to change notification settings - Fork 3k
Duplicate of#18812
Labels
Description
Hello, here's an issue I stumbled upon.
from typing import Generic, Type
from typing_extensions import TypeVar
class Interface: ...
_T = TypeVar("_T", bound=Interface, default=Interface)
class MyGeneric(Generic[_T]):
def __init__(self) -> None:
super().__init__()
self._value: Type[_T] = Interface
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.
from typing import Generic, Type
from typing_extensions import TypeVar
class Interface: ...
_T = TypeVar("_T", bound=Interface, default=Interface)
class MyGeneric(Generic[_T]):
def __init__(self, my_val: Type[_T] = Interface) -> None:
super().__init__()
self._value = my_val
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 the default
of TypeVar
in that case. At least, that's what I would expect.
Is this intended behavior?
Metadata
Metadata
Assignees
Labels
Projects
Milestone
Relationships
Development
Select code repository
Activity
brianschubert commentedon Apr 9, 2025
I think mypy is correct to reject this. The assignment
self._value: Type[_T] = Interface
isn't sound,_T
since_T
may be bound to a subtype ofInterface
. Consider for example:s3rius commentedon Apr 9, 2025
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?
A5rocks commentedon Apr 13, 2025
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?
sterliakov commentedon Apr 22, 2025
This is very similar to #3737 and #18812, the latter exactly about typevar
default
and defaults in generic classes.Do you need to provide any default implementation? I'd recommend going a level deeper and providing the default implementation that depends on
_T
in a separate subclass. RemoveInterface
default argument, let subclasses take care of that. Something like (untested)