Associated types on generics
Nobody has claimed this yet.
- Dominant language
- Python
- Stars
- 20.6k
- Forks
- 3.3k
- PR merge metrics
- PR metrics pending
Description
-
Request Type: Feature Request
-
Mock-up repro (more detailed mock-up here):
import abc import typing # Define two base types `ABase` & `BBase` with a similar interface, # that each return a different object type `AValue` & `BValue` from # some method # # The object type is also reexposed as a class attribute on the # respective base type for easier access. class AValue: value: bytes def __init__(self, value: bytes): self.value = value class ABase(metaclass=abc.ABCMeta): VALUE_T = AValue @abc.abstractmethod def get_some_value(self) -> AValue: ... class BValue: value: str def __init__(self, value: str): self.value = value class BBase(metaclass=abc.ABCMeta): VALUE_T = BValue @abc.abstractmethod def get_some_value(self) -> BValue: ... # Define generic type over the two defined above AnyBase = typing.TypeVar("AnyBase", ABase, BBase) # # HOW WOULD I NAME THE RETURN TYPE IN THE NEXT LINE? # # In particular note that the return type could not be just `AnyBase` # (over which we are generic) since we aren't returning *that* type, # but some other type determined by which type `AnyBase` is. def magic_convert(input: AnyBase) -> AnyBase.VALUE_T: #??? return input.VALUE_T(self.get_some_value().value * 2)``` -
Actual behaviour: There does seem to be anything like
AnyBase.VALUE_Tavailable for use inmypyand the given syntax results in both type-time and runtime errors. -
Expected behaviour: Some way to do this.
-
mypy version: 0.730
-
Python version: 3.7 (Debian)
-
mypy flags: None
I used some title that probably is close to the real (type theory) name of this feature, feel free to change it to something more fitting. 🙂
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start with the Python 3.7 reproduction in the issue and read the linked detailed mock-up to understand the desired associated-type relationship. Define what supported syntax and type-checking behavior should look like for the generic return type, including the shown magic_convert example; the issue is done when mypy can express and validate that relationship without the reported type-time or runtime errors.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- devtools
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Needs clarification
- Newbie friendliness
- 30/100