frozenlist.py 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. from collections.abc import MutableSequence
  2. from functools import total_ordering
  3. from .helpers import NO_EXTENSIONS
  4. @total_ordering
  5. class FrozenList(MutableSequence):
  6. __slots__ = ("_frozen", "_items")
  7. def __init__(self, items=None):
  8. self._frozen = False
  9. if items is not None:
  10. items = list(items)
  11. else:
  12. items = []
  13. self._items = items
  14. @property
  15. def frozen(self):
  16. return self._frozen
  17. def freeze(self):
  18. self._frozen = True
  19. def __getitem__(self, index):
  20. return self._items[index]
  21. def __setitem__(self, index, value):
  22. if self._frozen:
  23. raise RuntimeError("Cannot modify frozen list.")
  24. self._items[index] = value
  25. def __delitem__(self, index):
  26. if self._frozen:
  27. raise RuntimeError("Cannot modify frozen list.")
  28. del self._items[index]
  29. def __len__(self):
  30. return self._items.__len__()
  31. def __iter__(self):
  32. return self._items.__iter__()
  33. def __reversed__(self):
  34. return self._items.__reversed__()
  35. def __eq__(self, other):
  36. return list(self) == other
  37. def __le__(self, other):
  38. return list(self) <= other
  39. def insert(self, pos, item):
  40. if self._frozen:
  41. raise RuntimeError("Cannot modify frozen list.")
  42. self._items.insert(pos, item)
  43. def __repr__(self):
  44. return f"<FrozenList(frozen={self._frozen}, {self._items!r})>"
  45. PyFrozenList = FrozenList
  46. try:
  47. from aiohttp._frozenlist import FrozenList as CFrozenList # type: ignore
  48. if not NO_EXTENSIONS:
  49. FrozenList = CFrozenList # type: ignore
  50. except ImportError: # pragma: no cover
  51. pass