2

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
mon
  • 18,789
  • 22
  • 112
  • 205
  • 1
    This doesn't test for slicing specifically; are you looking for something which tests that an object can be sliced, or are you looking for something that does the same test as this code? – kaya3 Apr 23 '23 at 01:50
  • Usually the answer to this question is that you should try to slice the object (in whatever code needs to do that) and be prepared to catch an exception if it fails. – fakedad Apr 23 '23 at 02:06
  • 1
    Also, I don't think there is an answer to this question in general that doesn't involve inspecting the source code. Whether an object supports slicing depends only on how the object's `__getitem__` method is implemented. – fakedad Apr 23 '23 at 02:11
  • I don't see any indication that `Sequence` (as defined in `abc` or otherwise) requires or supports indexing with a `Slice` object. Yes, indexing for strings and lists is basically the same, and `ndarray` tries where practical to do the same. But as shown by the `np.lib.indexing_tricks` it is possible to define a class with a `__getitem__` that does quite different things with `Slice`. Indexing passes an object or tuple to the instance; it's the `__getitem__` code that determines how that argument is used. – hpaulj Apr 23 '23 at 15:53
  • `"__getitem__" in dir(object)` is generally not the correct approach, rather, you want `hasattr(object, "__getitem__")` (`dir` will usually work, but technically, it is merely a convenience method that shouldn't be relied on to give you reliable info) – juanpa.arrivillaga Apr 27 '23 at 21:30

1 Answers1

1

In Python, it's often better to ask forgiveness than permission.

def can_slice(my_sequence) -> bool:
    try:
        my_sequence[0]
        return True
    except TypeError:
        return False
Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116