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.
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 :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With