Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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 a mixin class that may be used on classes that are based
- # on either `ABase` or `BBase`
- #
- # Not currently available: https://github.com/python/mypy/issues/7191
- AnyBase = typing.TypeVar("AnyBase", ABase, BBase)
- SomeMixinSelf = typing.TypeVar("SomeMixinSelf", bound=AnyBase)
- class SomeMixin(typing.Generic[AnyBase]):
- #
- # HOW WOULD I NAME THE SELF AND RETURN TYPES IN THE NEXT LINE?
- #
- # In particular note that the return type could not be something
- # like `AnyBase` (over which we are generic) since we wouldn't return
- # *that* type, but some other determined by which type `AnyBase` is.
- def transformed_value(self: SomeMixinSelf) -> AnyBase.VALUE_T:
- return self.VALUE_T(self.get_some_value().value * 2)
- # Examples of how the final classes using the above mixin would be used
- class AImpl(SomeMixin, ABase):
- def get_some_value(self) -> AValue:
- return AValue(b"blab")
- class BImpl(SomeMixin, BBase):
- def get_some_value(self) -> BValue:
- return BValue("blub")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement