如何输入提示真正可选的参数

问题描述 投票:0回答:1

我有这个功能并带有类型提示:

class HDF5DataTypes(Enum):
    SCALAR = "scalar"
    ARRAY = "array"
    UNKNOWN = "unknown"

@overload
def index_hdf5_to_value(file_or_group: Union[h5py.File, h5py.Group], indexes: List[str], expected_output_type: Literal[HDF5DataTypes.SCALAR]) -> np.float_:
    ...
@overload
def index_hdf5_to_value(file_or_group: Union[h5py.File, h5py.Group], indexes: List[str], expected_output_type: Literal[HDF5DataTypes.ARRAY]) -> npt.NDArray:
    ...
@overload
def index_hdf5_to_value(file_or_group: Union[h5py.File, h5py.Group], indexes: List[str], expected_output_type: Literal[HDF5DataTypes.UNKNOWN]) -> Union[npt.NDArray, np.float_]:
    ...
def index_hdf5_to_value(file_or_group: Union[h5py.File, h5py.Group], indexes: List[str], expected_output_type: HDF5DataTypes=HDF5DataTypes.UNKNOWN) -> Union[npt.NDArray, np.float_]:
    '''Given a file or group, returns the output of indexing the file or group with the indexes down until it gets to the dataset, at which point it gives back the value of the dataset (either the scalar or numpy array).
    '''
    dataset = index_hdf5(file_or_group, indexes, h5py.Dataset)
    if len(dataset.shape) == 0:
        if expected_output_type == HDF5DataTypes.ARRAY:
            raise ValueError(f"Expected output to be an array, but it was a scalar")
        return cast(np.float_, dataset[()])
    else:
        if expected_output_type == HDF5DataTypes.SCALAR:
            raise ValueError(f"Expected output to be a scalar, but it was an array")
        return cast(npt.NDArray, dataset[:])

但是,当我用

index_hdf5_to_value(hdf5_file, ["key1", "key2"])
调用它时,我收到错误
No overloads for "index_hdf5_to_value" match the provided arguments Argument types: (File, list[str])

总之,因为我没有提供第三个参数而感到不安。

现在,我可以将第三个参数键入提示为

Optional
,但随后我担心这暗示使用
index_hdf5_to_value(hdf5_file, ["key1", "key2"], None)
调用函数是可以的,但事实并非如此。

我应该如何正确地键入提示此函数,以告诉用户第三个参数是可选的,但不能设置为

None
? (也就是说,它是可选的,但不是
Optional
。)

python type-hinting pylance
1个回答
0
投票

尽管有这个名字,

Optional
并不意味着“可选”。意思是“可能
None
”。用
Optional
注释参数没有帮助 - mypy 仍然不允许你省略参数。

您需要提供一个重载,实际上接受在没有

expected_output_type
参数的情况下被调用:

@overload
def index_hdf5_to_value(file_or_group: Union[h5py.File, h5py.Group], indexes: List[str]) -> Union[npt.NDArray, np.float_]:
    ...
© www.soinside.com 2019 - 2024. All rights reserved.