How to create custom TensorDetail extensions
masterYou can extend torchtyping to check arbitrary properties of a tensor by subclassing torchtyping.TensorDetail. A custom detail must implement three methods:
check(self, tensor: Tensor) -> bool: ReturnsTrueif the tensor satisfies the condition.__repr__(self) -> str: Returns a string describing the detail (used in error messages).tensor_repr(cls, tensor: Tensor) -> str: Returns a string describing the actual property found on the tensor (used in error messages).
Pass instances of your custom detail to TensorType to enforce the check.
from torch import rand, Tensor
from torchtyping import TensorDetail, TensorType
from typeguard import typechecked
class FooDetail(TensorDetail):
def __init__(self, foo):
super().__init__()
self.foo = foo
def check(self, tensor: Tensor) -> bool:
return hasattr(tensor, "foo") and tensor.foo == self.foo
def __repr__(self) -> str:
return f"FooDetail({self.foo})"
@classmethod
def tensor_repr(cls, tensor: Tensor) -> str:
if hasattr(tensor, "foo"):
return f"FooDetail({tensor.foo})"
else:
return ""
@typechecked
def foo_checker(tensor: TensorType[float, FooDetail("good-foo")]):
pass