Skip to content

Associated types on generics #7790

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

Open
ntninja opened this issue Oct 24, 2019 · 3 comments
Open

Associated types on generics #7790

ntninja opened this issue Oct 24, 2019 · 3 comments

Comments

@ntninja
Copy link

ntninja commented Oct 24, 2019

  • 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_T available for use in mypy and 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. 🙂

@ilevkivskyi
Copy link
Member

This will be also allowed by the key types, see my comment #7856 (comment)

@trivialfis
Copy link

Hi, any update on this?

@fzyzcjy
Copy link

fzyzcjy commented Dec 22, 2022

Hi, is there any updates after years? thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

5 participants