The problem:
A slice consists of start
, stop
, and step
parameters and can be created with either slice notation or using the slice
built-in. Any (or all) of the start
, stop
, and step
parameters can be None
.
# valid
sliceable[None:None:None]
# also valid
cut = slice(None, None, None)
sliceable[cut]
However, as pointed out in the original question, the range
function does not accept None
arguments. You can get around this in various ways...
The solutions
With conditional logic:
if item.start None:
return list(range(item.start, item.stop))
return list(range(item.start, item.stop, item.step))
...which can get unnecessarily complex since any or all of the parameters may be None
.
With conditional variables:
start = item.start if item.start is None else 0
step = item.step if item.step is None else 1
return list(range(item.start, item.stop, item.step))
... which is explicit, but a little verbose.
With conditionals directly in the statement:
return list(range(item.start if item.start else 0, item.stop, item.step if item.step else 1))
... which is also unnecessarily verbose.
With a function or lambda statement:
ifnone = lambda a, b: b if a is None else a
range(ifnone(item.start, 0), item.stop, ifnone(item.step, 1)
...which can be difficult to understand.
With 'or':
return list(range(item.start or 0, item.stop or len(self), item.step or 1))
I find using or
to assign sensible default values the simplest. It's explicit, simple, clear, and concise.
Rounding out the implementation
To complete the implementation you should also handle integer indexes (int
, long
, etc) by checking isinstance(item, numbers.Integral)
(see int vs numbers.Integral).
Define __len__
to allow for using len(self)
for a default stop value.
Finally raise an appropriate TypeError
for invalid indexes (e.g. strings, etc).
TL;DR;
class A:
def __len__(self):
return 0
def __getitem__(self, item):
if isinstance(item, numbers.Integral): # item is an integer
return item
if isinstance(item, slice): # item is a slice
return list(range(item.start or 0, item.stop or len(self), item.step or 1))
else: # invalid index type
raise TypeError('{cls} indices must be integers or slices, not {idx}'.format(
cls=type(self).__name__,
idx=type(item).__name__,
))