Advertisement
Guest User

Untitled

a guest
Oct 24th, 2019
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.70 KB | None | 0 0
  1. import abc
  2. import typing
  3.  
  4.  
  5. # Define two base types `ABase` & `BBase` with a similar interface,
  6. # that each return a different object type `AValue` & `BValue` from
  7. # some method
  8. #
  9. # The object type is also reexposed as a class attribute on the
  10. # respective base type for easier access.
  11. class AValue:
  12.     value: bytes
  13.    
  14.     def __init__(self, value: bytes):
  15.         self.value = value
  16.  
  17. class ABase(metaclass=abc.ABCMeta):
  18.     VALUE_T = AValue
  19.    
  20.     @abc.abstractmethod
  21.     def get_some_value(self) -> AValue: ...
  22.  
  23.  
  24. class BValue:
  25.     value: str
  26.    
  27.     def __init__(self, value: str):
  28.         self.value = value
  29.  
  30. class BBase(metaclass=abc.ABCMeta):
  31.     VALUE_T = BValue
  32.    
  33.     @abc.abstractmethod
  34.     def get_some_value(self) -> BValue: ...
  35.  
  36.  
  37.  
  38. # Define a mixin class that may be used on classes that are based
  39. # on either `ABase` or `BBase`
  40. #
  41. # Not currently available: https://github.com/python/mypy/issues/7191
  42.  
  43.  
  44. AnyBase = typing.TypeVar("AnyBase", ABase, BBase)
  45. SomeMixinSelf = typing.TypeVar("SomeMixinSelf", bound=AnyBase)
  46.  
  47. class SomeMixin(typing.Generic[AnyBase]):
  48.     #
  49.     # HOW WOULD I NAME THE SELF AND RETURN TYPES IN THE NEXT LINE?
  50.     #
  51.     # In particular note that the return type could not be something
  52.     # like `AnyBase` (over which we are generic) since we wouldn't return
  53.     # *that* type, but some other determined by which type `AnyBase` is.
  54.     def transformed_value(self: SomeMixinSelf) -> AnyBase.VALUE_T:
  55.         return self.VALUE_T(self.get_some_value().value * 2)
  56.  
  57.  
  58. # Examples of how the final classes using the above mixin would be used
  59. class AImpl(SomeMixin, ABase):
  60.     def get_some_value(self) -> AValue:
  61.         return AValue(b"blab")
  62.  
  63.  
  64. class BImpl(SomeMixin, BBase):
  65.     def get_some_value(self) -> BValue:
  66.         return BValue("blub")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement