Created
January 4, 2020 01:30
-
-
Save daltonmatos/cd423d265ba092300f65ac00af37c8c4 to your computer and use it in GitHub Desktop.
Blog post: Chamando funções Python com assinatura dinâmica Baseada em Typehint
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
from typing import Dict, Type, Any, Callable, get_type_hints, Coroutine, TypeVar | |
T = TypeVar("T") | |
types_registry: Dict[Type, Any] = dict() | |
async def call_func( | |
f: Callable[..., Coroutine[Any, Any, T]], registry: Dict[Type, Any] | |
) -> T: | |
types_for_func = get_type_hints(f) | |
values_for_call = {} | |
for param_name, param_type in types_for_func.items(): | |
values_for_call[param_name] = types_registry[param_type] | |
return await f(**values_for_call) | |
async def func(a: int, b: str) -> str: | |
return f"int is {a}, str is {b}" | |
async def main(): | |
num = 42 | |
name = "Dalton" | |
types_registry[int] = 42 | |
types_registry[str] = name | |
print(await func(num, name)) | |
print(await call_func(func, types_registry)) | |
asyncio.run(main()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment