Python Type Hinting: Output Type Based on Input Type

pythonpython-typingtype-hinting

Consider the following function

import typing
def make_list(el : typing.Any):
    return [el, el]

How do I hint that it returns

typing.List[type(el)]

Best Answer

That's what TypeVar is for:

from typing import TypeVar, List

T = TypeVar('T')

def make_list(el: T) -> List[T]:
    return [el, el]
Related Question