14

Suppose I want to write a generic class using mypy, but the type argument for the class is itself a generic type. For example:

from typing import TypeVar, Generic, Callable
A = TypeVar("A")
B = TypeVar("B")
T = TypeVar("T")
class FunctorInstance(Generic[T]):
 def __init__(self, map: Callable[[Callable[[A], B], T[A]], T[B]]):
 self._map = map
 def map(self, x: T[A], f: Callable[[A], B]) -> T[B]:
 return self._map(f, x)

When I try to call mypy in the definition above I get an error:

$ mypy typeclasses.py 
typeclasses.py:9: error: Type variable "T" used with arguments
typeclasses.py:12: error: Type variable "T" used with arguments 

I tried adding constraints to the T TypeVar's definition but failed to make this work. Is it possible to do this?

InSync
12.2k5 gold badges22 silver badges60 bronze badges
asked Jan 9, 2019 at 20:46
0

2 Answers 2

9

Currently, as of writing, the mypy project does not support higher-kinded types. See the following github issue:

https://github.com/python/typing/issues/548

answered Jan 9, 2019 at 23:58
Sign up to request clarification or add additional context in comments.

Comments

6

The returns package now provides some third party support for HKTs.

To copy a snippet from their docs

>>> from returns.primitives.hkt import Kind1
>>> from returns.interfaces.container import Container1
>>> from typing import TypeVar
>>> T = TypeVar('T', bound=Container1)
>>> def to_str(arg: Kind1[T, int]) -> Kind1[T, str]:
... ...

Your Functor would be sth like

from typing import TypeVar, Generic, Callable
A = TypeVar("A")
B = TypeVar("B")
T = TypeVar("T")
class FunctorInstance(Generic[T]):
 def __init__(
 self, map: Callable[[Callable[[A], B], Kind1[T, A]], Kind1[T, B]]
 ):
 self._map = map
 def map(self, x: Kind1[T, A], f: Callable[[A], B]) -> Kind1[T, B]:
 return self._map(f, x)
answered Nov 15, 2020 at 16:55

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.