Source code

Download source archive ↓

src/openpyxl/utils/indexed_list.py

1# Copyright (c) 2010-2024 openpyxl
2
3
4class IndexedList(list):
5    """
6    List with optimised access by value
7    Based on Alex Martelli's recipe
8
9    http://code.activestate.com/recipes/52303-the-auxiliary-dictionary-idiom-for-sequences-with-/
10    """
11
12    _dict = {}
13
14    def __init__(self, iterable=None):
15        self.clean = True
16        self._dict = {}
17        if iterable is not None:
18            self.clean = False
19            for idx, val in enumerate(iterable):
20                self._dict[val] = idx
21                list.append(self, val)
22
23    def _rebuild_dict(self):
24        self._dict = {}
25        idx = 0
26        for value in self:
27            if value not in self._dict:
28                self._dict[value] = idx
29                idx += 1
30        self.clean = True
31
32    def __contains__(self, value):
33        if not self.clean:
34            self._rebuild_dict()
35        return value in self._dict
36
37    def index(self, value):
38        if value in self:
39            return self._dict[value]
40        raise ValueError
41
42    def append(self, value):
43        if value not in self._dict:
44            self._dict[value] = len(self)
45            list.append(self, value)
46
47    def add(self, value):
48        self.append(value)
49        return self._dict[value]