lazyTools.py 1020 B

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. from collections import UserDict, UserList
  2. __all__ = ["LazyDict", "LazyList"]
  3. class LazyDict(UserDict):
  4. def __init__(self, data):
  5. super().__init__()
  6. self.data = data
  7. def __getitem__(self, k):
  8. v = self.data[k]
  9. if callable(v):
  10. v = v(k)
  11. self.data[k] = v
  12. return v
  13. class LazyList(UserList):
  14. def __getitem__(self, k):
  15. if isinstance(k, slice):
  16. indices = range(*k.indices(len(self)))
  17. return [self[i] for i in indices]
  18. v = self.data[k]
  19. if callable(v):
  20. v = v(k)
  21. self.data[k] = v
  22. return v
  23. def __add__(self, other):
  24. if isinstance(other, LazyList):
  25. other = list(other)
  26. elif isinstance(other, list):
  27. pass
  28. else:
  29. return NotImplemented
  30. return list(self) + other
  31. def __radd__(self, other):
  32. if not isinstance(other, list):
  33. return NotImplemented
  34. return other + list(self)