Python中是否有TypeScript Parameters/ConstructorParameters工具类型的等效实现?
Python 中 TypeScript Parameters/ConstructorParameters 的等效实现
1. 对应 Parameters 的类型工具
Python 3.10+ 的标准库 typing 模块(低版本可使用 typing_extensions)提供了 ParamSpec 和 TypeVar,可以实现类似 TypeScript Parameters 的功能,用于提取函数的参数类型:
from typing import Callable, ParamSpec, TypeVar P = ParamSpec("P") R = TypeVar("R") def extract_params(func: Callable[P, R]) -> P.args: pass def sample_func(a: int, b: str) -> bool: return True # 类型检查器会推断 extract_params(sample_func) 的返回类型为 tuple[int, str]
2. 为 foo_config 添加与 FooSdk.__init__ 对齐的类型注解
要让 foo_config 严格匹配 FooSdk.__init__ 的关键字参数(排除 self),有两种常用方案:
方案一:手动定义 TypedDict
直接创建对应 __init__ 参数的 TypedDict,明确必填和可选参数:
from typing import TypedDict, List # 替换 something/something_else 为实际类型 class FooConfig(TypedDict, total=False): config_a: something config_b: something_else # 若 __init__ 的 **kwargs 有特定类型,可在此添加对应字段 class FooSdk: def __init__(self, config_a: something, config_b: something_else, **kwargs): pass def do_something_with_foo(foo_config: FooConfig, another_argument: List): temp_foo = FooSdk(**foo_config) # ... 业务逻辑
方案二:自动提取构造函数参数类型(Python 3.11+)
通过 inspect 模块提取构造函数的签名,自动生成对应的 TypedDict,避免手动同步参数:
from typing import TypedDict, List import inspect def generate_constructor_config(cls) -> type[TypedDict]: sig = inspect.signature(cls.__init__) field_types = {} for param_name, param in sig.parameters.items(): if param_name == "self": continue field_types[param_name] = param.annotation return TypedDict(f"{cls.__name__}Config", field_types, total=False) class FooSdk: def __init__(self, config_a: str, config_b: int, **kwargs): pass # 自动生成与 FooSdk.__init__ 参数对齐的类型 FooSdkConfig = generate_constructor_config(FooSdk) def do_something_with_foo(foo_config: FooSdkConfig, another_argument: List): temp_foo = FooSdk(**foo_config) # ... 业务逻辑
注:静态类型检查工具(如 mypy)对这种动态生成的类型支持有限,若需严格的类型校验,手动定义 TypedDict 更可靠。
内容的提问来源于stack exchange,提问作者dan-man
相关产品推荐
相关产品推荐

