dry-python / classes

Smart, pythonic, ad-hoc, typed polymorphism for Python
https://classes.rtfd.io
BSD 2-Clause "Simplified" License
652 stars 24 forks source link

Typeclasses with several methods #83

Open sobolevn opened 4 years ago

sobolevn commented 4 years ago

There's a common use-case when we need to create a type-class with several methods. Like:

class Functor(Protocol[T]):
    def map(self, function: Callable[[T], Functor[V]]) -> Functor[V]:
        ...

    @classmethod
    def from_value(cls, inner_value: V) -> Functor[V]:
        ...

Currently, there's no way we can do that.

I propose something like this:

@typeclass
class Functor(Protocol[T]):
    def map(self, function: Callable[[T], Functor[V]]) -> Functor[V]:
        ...

    @classmethod
    def from_value(cls, inner_value: V) -> Functor[V]:
        ...

I am not sure how to bound it to the actual implementation.

sobolevn commented 4 years ago
@Functor.instance
class Maybe(Generic[T]):
    def map(self, function: Callable[[T], Maybe[V]]) -> Maybe[V]:
        ...

    @classmethod
    def from_value(cls, inner_value: V) -> Maybe[V]:
        ...
sobolevn commented 4 years ago

How is it different from a simple protocol?