Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python type hinting, output type depends on input type

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)]
like image 362
MrJ Avatar asked Jan 02 '23 09:01

MrJ


1 Answers

That's what TypeVar is for:

from typing import TypeVar, List

T = TypeVar('T')

def make_list(el: T) -> List[T]:
    return [el, el]
like image 182
deceze Avatar answered Jan 16 '23 14:01

deceze