Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a TypedDict corresponding to a function signature?

Say I've got a function signature like this:

def any_foo(
    bar: Bar,
    with_baz: Optional[Baz] = None,
    with_datetime: Optional[datetime] = None,
    effective: Optional[bool] = False,
) -> Foo

I could of course just copy its declaration and fiddle with it enough to create the following TypedDict:

AnyFooParameters = TypedDict(
    "AnyFooParameters",
    {
        bar: Bar,
        with_baz: Optional[Baz],
        with_datetime: Optional[datetime],
        effective: Optional[bool]
    }
)

But this seems like such a straight-forward transformation that I wonder whether there's some easy way to create this TypedDict (or at least the name: type pairs) straight from the function.

like image 805
l0b0 Avatar asked Sep 15 '20 01:09

l0b0


1 Answers

The result of any_foo.__annotations__ is exactly what you want. For example:

from typing import Optional
def any_foo(
    req_int: int,
    opt_float: Optional[float] = None,
    opt_str: Optional[str] = None,
    opt_bool: Optional[bool] = False,
) -> int:
    pass

And with any_foo.__annotations__, you can get this:

{'req_int': int,
 'opt_float': typing.Optional[float],
 'opt_str': typing.Optional[str],
 'opt_bool': typing.Optional[bool],
 'return': int}

Note you can access to the type of return value by the return key.

BTW, since return is a reserved keyword, you cannot name an argument as return so there's no need to warry about a duplicate key :)

like image 178
C.K. Avatar answered Mar 03 '23 00:03

C.K.