-1

How can I typehint that something should have the same type as earlier?

def mymap(xs: [T], func: T -> V): -> [V]:
    return [func(x) for x in xs]
theonlygusti
  • 11,032
  • 11
  • 64
  • 119

1 Answers1

2

You can do this with TypeVar

from typing import Callable, List, TypeVar


T = TypeVar('T')
V = TypeVar('V')


def mymap(items: List[T], fn: Callable[[T], V]) -> List[V]:
    return [fn(e) for e in items]
kingkupps
  • 3,284
  • 2
  • 16
  • 28
  • do I have to use `List` and `Callable` too? – theonlygusti Jan 17 '22 at 11:25
  • It depends on what `items` really is and which version of Python you're using. You should definitely use `Callable` but `List` could be replaced by `Set` or `Dict` for example. If you're using (I think) Python 3.9+ you can use `list` directly instead of `typing.List`. – kingkupps Jan 17 '22 at 16:33