gpt4 book ai didi

python - 装饰器更改通用返回类型时的键入函数

转载 作者:行者123 更新时间:2023-12-05 02:45:33 29 4
gpt4 key购买 nike

这类似于 Typing function when decorator change return type但这次使用通用返回类型:

from typing import Generic, TypeVar, Generic, Callable, Any, cast

T = TypeVar('T')

class Container(Generic[T]):
def __init__(self, item: T):
self.item: T = item

def my_decorator(f: Callable[..., T]) -> Callable[..., Container[T]]:

def wrapper(*args: Any, **kwargs: Any) -> Container[T]:
return Container(f(*args, **kwargs))

return cast(Callable[..., Container[T]], wrapper)

@my_decorator
def my_func(i: int, s: str) -> bool: ...

reveal_type(my_func) # Revealed type is 'def (*Any, **Any) -> file.Container[builtins.bool*]

需要哪个 mypy 魔法来保持 my_func参数类型完整?

使用 typing.Protocol看起来很有希望,但我不知道如何让它发挥作用。

最佳答案

使用 Callable[..., T] 是目前最好的注解方式。

PEP 612 引入了 ParamSpec,它可以像 TypeVar 一样使用,将解决您的问题。目前计划用于 Python 3.10,并将使用 typing_extensions

支持旧版本

在那里你会写:

T = TypeVar('T')
P = ParamSpec('P')

def my_decorator(f: Callable[P, T]) -> Callable[P, Container[T]]:

def wrapper(*args: Any, **kwargs: Any) -> Container[T]:
return Container(f(*args, **kwargs))

return cast(Callable[P, Container[T]], wrapper)

mypy 对 PEP 612 的支持尚未完成:https://github.com/python/mypy/issues/8645 .与 pytype(Google 的 python 类型检查器)相同。

pyright(微软的 python typechecker)和 pyre(facebook 的 python typechecker)已经支持 PEP 612

关于python - 装饰器更改通用返回类型时的键入函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65936408/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com