目前,我正在使用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
实现装饰器
我知道我可以{
作为对使用键入信息包装方法的建议的回应,我将分享我的实际用例
我正在使用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
,它的形状就会不同。它还需要简短,以便我可以使用它作为文档,以及捕捉真正发生的bug
安装:
描述
可以通过“检查类型”功能根据类型或注释检查对象
如果检查成功,该函数将返回None,如果出现错误,则会引发TypeError
请注意,此函数不会递归检查类的属性等
链接:https://pypi.org/project/runtime-type-checker/
然后只需向它们添加类型提示
至少有两种方法可以做到这一点
第一个选项是,创建新函数的唯一原因是向其添加所需的类型提示,例如:
第二个选项是直接写入它们的^{} 特殊属性,然后修饰它
(这不适用于内置函数和/或c扩展,仅适用于使用纯python创建的函数和/或c扩展,因此您不能对math.cos或numpy.array这样做)
对于某些内联版本,似乎很简单,不可能为函数动态执行此操作: 7.2.2. Annotated assignment statements
由于这些信息在运行时丢失,没有任何恶意的装饰程序可以知道函数中的给定变量是以某种方式注释的,因此这只是可以直接查看源代码(例如IDE)的静态类型检查器的工件,因此,如果您希望在运行时将这些类型检查添加到代码中,则需要一个编译器。。。如果你想这样做,那么你可能需要考虑是否更好地使用一种不同的语言来提供一种本地类型的检查和执行机制。p>
除此之外,使用我建议的解决方案之一,或者默认为
assert
、isinstance
,等等。。。那看起来是唯一的办法相关问题 更多 >
编程相关推荐