Skip to content

Type for classes expecting a certain generic parameter #7791

Closed as not planned
@ntninja

Description

@ntninja
  • Request Type: Feature Request

  • Mock-up repro (more detailed mock-up here):

    import abc
    import typing
    
    
    # Define two similar base types `ABase` & `BBase` doing their thing
    class ABase(metaclass=abc.ABCMeta):
    	@abc.abstractmethod
    	def get_some_value(self) -> str: ...
    
    class BBase(metaclass=abc.ABCMeta):
    	@abc.abstractmethod
    	def get_some_value(self) -> bytes: ...
    
    
    # Define generic type over the two types defined above
    AnyBase = typing.TypeVar("AnyBase", ABase, BBase)
    
    
    # Define function that accepts a class as a parameter and generates two classes
    # based on the above types using the received class as a mixin
    def generate_subclasses(cls: typing.Type[typing.Generic[AnyBase]]) -> (ABase, BBase):
    	class AClass(cls[ABase], ABase): ...
    	class BClass(cls[BBase], BBase): ...
    	return AClass, BClass
    
    
    # Usage of the above
    class Mixin(typing.Generic[AnyBase]): ...
    A, B = generate_subclasses(Mixin)
  • Actual behaviour: There does seem to be any way in mypy to define a parameter as expecting “a class that is generic over some known TypeVar T”. Instead mypy lets me know that “Variable "typing.Generic" is not valid as a type” and at runtime “TypeError: typing.Generic[~AnyBase] is not valid as type argument” is raised.

  • Expected behaviour: Some way to do this.

  • mypy version: 0.730

  • Python version: 3.7 (Debian)

  • mypy flags: None

It makes more sense when you see this in full as part of a cooperative multiple inheritance scheme involving #7790 and #7191… This example is indeed not very strongly motivated on its own, but it should work as nevertheless.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions