indexing.py 780 B

123456789101112131415161718192021222324252627282930
  1. # created: 23.04.2018
  2. # Copyright (c) 2018 Manfred Moitzi
  3. # License: MIT License
  4. from typing import Iterable
  5. class Index:
  6. def __init__(self, item):
  7. try:
  8. self.length = len(item)
  9. except TypeError:
  10. self.length = int(item)
  11. def index(self, item: int, error=None) -> int:
  12. if item < 0:
  13. result = self.length + int(item)
  14. else:
  15. result = int(item)
  16. if error and not (0 <= result < self.length):
  17. raise error('index out of range')
  18. return result
  19. def slicing(self, *args) -> Iterable[int]:
  20. if isinstance(args[0], slice):
  21. s = args[0]
  22. else:
  23. s = slice(*args)
  24. return range(*s.indices(self.length))