Skip to main content
 首页 » 编程设计

python之__getitem__/__setitem__ 应该使用哪个异常和不支持的切片步长

2024年10月24日15jpfss

我在第 3 方模块中找到了这段代码,在这种情况下,该模块忽略了 foo[::step] 或 key.step。

def __getitem__(self, key): 
    if isinstance(key, slice): 
        return self._sub_slice(key.start, key.stop) 
    if self._is_in_range(key): 
        return self._tree[key] 
    else: 
        raise KeyError(key) 

虽然支持步骤是理想的,但假设这不会被支持,我想添加一个异常(exception),否则 foo[a:b:-1] for eg 将被忽略切片中的 -1。

例如:

if key.step not in {None, 1}: 
    raise Exception("only a step size of 1 is supported") 

所以我的问题是,对于有效但不受支持的切片步骤, 应该使用哪种异常类型?

请您参考如下方法:

ValueError

Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.

https://docs.python.org/3/library/exceptions.html#ValueError

“正确的类型但不合适的值”似乎很符合您的描述。