【发布时间】:2021-12-08 10:25:00
【问题描述】:
目前我正在使用typeguard.typechecked 来装饰我的函数并检查重要函数的输入和输出。
from typeguard import typechecked
@typechecked # Gives me an error if argument/return types don't match the hints
def takes_int_makes_float(x: int) -> float:
return float(x)
但是,如果我想检查来自我无法控制的函数的类型,并在类型不是我想要的类型时出错?
@proposed_decorator
def does_something_interesting():
# Implicitly assert that this is the right type.
# Note that this is valid Python code already, and works as a hint to my IDE.
x: float = makes_float_or_tuple()
print(x)
有没有办法做到这一点?当然可以使用 ast 使用装饰器来实现。
我知道我可以 assert isinstance 或类似的东西,但自动隐式方法会更好。
编辑:
作为对使用键入信息包装方法的建议的回应,我将分享我的实际用例。
我正在使用 torchtyping 记录并确保我的 PyTorch 张量的形状。
from torchtyping import TensorType
import torch
def interesting_reshaping_method(x: TensorType['batch', 'num_points', 'point_dim']):
lengths: TensorType['batch', 'num_points', 1] = torch.norm(x, dim=2, keepdim=True)
# ... do something that requires this exact shape to do what I want,
# but will fail silently if the shape isn't what I want.
在这种情况下,我需要明确检查张量的类型,如果我使用了keepdim=False 或一些不同的dim,它的形状会有所不同。它还需要简短,以便我可以将其用作文档并在真正发生的错误处发现错误。
【问题讨论】:
-
"显式优于隐式。" 〜python的禅。
-
那你为什么不把你想检查类型的函数做一个修饰版本呢?
-
@Copperfield 我对我想要的行为非常明确,我只是不想输入大量的样板。不在我要调用的函数周围使用装饰器的原因是因为库函数通常没有类型提示。
typechecked装饰器的typecheck_inline标志之类的东西会非常清楚。
标签: python decorator type-hinting typeguards