类型提示 torch.float 用于特殊形式类型提示
Type Hinting torch.float for special form type hint
我有一个函数可以接受 typing.Union
个类型,包括 torch.float
类型。但是,如果我使用带有 torch.float
的 typing.Union
类型作为参数,我会收到一个错误。这是一个例子:
from typing import Union
import torch
def fct(my_float_or_tensor: Union[torch.float, torch.Tensor]):
pass
我得到了错误
TypeError: Union[t0, t1, ...]: each t must be a type. Got torch.float32.
我做错了什么?
有趣的是,特殊类型 typing.Tuple
也会出现同样的问题,但如果我在类型提示时直接使用 torch.float
则不会。
There is a difference between "dtypes" and "types". torch.float
is a dtype
. For type hinting, use torch.FloatTensor
(还有其他的,例如DoubleTensor
、HalfTensor
等)
我有一个函数可以接受 typing.Union
个类型,包括 torch.float
类型。但是,如果我使用带有 torch.float
的 typing.Union
类型作为参数,我会收到一个错误。这是一个例子:
from typing import Union
import torch
def fct(my_float_or_tensor: Union[torch.float, torch.Tensor]):
pass
我得到了错误
TypeError: Union[t0, t1, ...]: each t must be a type. Got torch.float32.
我做错了什么?
有趣的是,特殊类型 typing.Tuple
也会出现同样的问题,但如果我在类型提示时直接使用 torch.float
则不会。
There is a difference between "dtypes" and "types". torch.float
is a dtype
. For type hinting, use torch.FloatTensor
(还有其他的,例如DoubleTensor
、HalfTensor
等)