2021-11-12 20:55:59 +08:00
|
|
|
import inspect
|
2021-11-21 12:36:44 +08:00
|
|
|
from typing import Any, Dict
|
2021-11-12 20:55:59 +08:00
|
|
|
|
2021-11-14 18:51:23 +08:00
|
|
|
from loguru import logger
|
|
|
|
from pydantic.typing import ForwardRef, evaluate_forwardref
|
2021-11-12 20:55:59 +08:00
|
|
|
|
2021-11-21 12:36:44 +08:00
|
|
|
from nonebot.typing import T_Handler
|
2021-11-12 20:55:59 +08:00
|
|
|
|
2021-11-21 12:36:44 +08:00
|
|
|
|
|
|
|
def get_typed_signature(func: T_Handler) -> inspect.Signature:
|
|
|
|
signature = inspect.signature(func)
|
|
|
|
globalns = getattr(func, "__globals__", {})
|
2021-11-12 20:55:59 +08:00
|
|
|
typed_params = [
|
|
|
|
inspect.Parameter(
|
|
|
|
name=param.name,
|
|
|
|
kind=param.kind,
|
|
|
|
default=param.default,
|
|
|
|
annotation=get_typed_annotation(param, globalns),
|
2021-11-22 23:21:26 +08:00
|
|
|
)
|
|
|
|
for param in signature.parameters.values()
|
2021-11-12 20:55:59 +08:00
|
|
|
]
|
|
|
|
typed_signature = inspect.Signature(typed_params)
|
|
|
|
return typed_signature
|
|
|
|
|
|
|
|
|
2021-11-22 23:21:26 +08:00
|
|
|
def get_typed_annotation(param: inspect.Parameter, globalns: Dict[str, Any]) -> Any:
|
2021-11-12 20:55:59 +08:00
|
|
|
annotation = param.annotation
|
|
|
|
if isinstance(annotation, str):
|
|
|
|
annotation = ForwardRef(annotation)
|
2021-11-14 18:51:23 +08:00
|
|
|
try:
|
|
|
|
annotation = evaluate_forwardref(annotation, globalns, globalns)
|
|
|
|
except Exception as e:
|
|
|
|
logger.opt(colors=True, exception=e).warning(
|
2021-11-22 23:21:26 +08:00
|
|
|
f'Unknown ForwardRef["{param.annotation}"] for parameter {param.name}'
|
2021-11-14 18:51:23 +08:00
|
|
|
)
|
|
|
|
return inspect.Parameter.empty
|
2021-11-12 20:55:59 +08:00
|
|
|
return annotation
|