Is this the right way to check if a Python object can be sliced or are there better/correct ways?
import typing
def can_slice(object) -> bool:
return "__getitem__" in dir(object)
I am looking for a way not using exception to test if an object can be sliced.
Update
The above can_slice
is incorrect because a dictionary has __getitem__
but cannot be sliced.
Cannot use typing.Sequence
because numpy array is not of type Sequence.
from typing import Sequence
isinstance(np.array([1,2,3]), Sequence)
---
False