Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to annotate Python function using return type of another function?

I am looking for some analogue of decltype in C++. What I am trying to accomplish is the following:

def f(a: int) -> List[Tuple(int, float)]
def g(a: List[int]) -> List[decltype(f)]

So the idea is to use type annotation of another function. The solution I found looks somehow clumsy:

def g(a: List[int])->f.__annotations__['return']

Basically, the question is whether there exists something like decltype (perhaps it should be called "return_type") or whether it's planned in further versions. I have also written a small function that illustrates possible use of this functionality:

def return_type(f: Callable):
   try:
       return get_type_hints(f)['return']
   except(KeyError, AttributeError):
       return Any
def g() -> return_type(f):

UPD As was suggested by Jim Fasarakis-Hilliard we can also use get_type_hints instead of annotations

like image 551
ig-melnyk Avatar asked Feb 08 '17 22:02

ig-melnyk


1 Answers

Nothing like that currently exists and no issue on the tracker for typing seem to indicate that it is planned. You're always welcome to create an issue and see how this is welcomed.

Currently your approach does the trick (that is assigns a type), the only change I'd introduce would be to use get_type_hints from typing rather than grabbing the __annotations__ attribute directly. Coupled with .get (since it returns a dict), could make this shorter, too:

def return_type(f):
    return get_type_hints(f).get('return', Any)

def g() -> return_type(f):

Which can of course be removed from the function and used in a single line if you're so inclined.

If the possibility of random objects being supplied to return_type exits, you'll need to catch the TypeError it raises and return your default Any:

def return_type(f):
    try:
        return get_type_hints(f).get('return', Any)
    except TypeError:
        return Any

Of course since this assigns a type dynamically you can't expect static type checkers to catch it, you need static hinting for that.

like image 158
Dimitris Fasarakis Hilliard Avatar answered Oct 20 '22 14:10

Dimitris Fasarakis Hilliard