~launchpad-pqm/launchpad/devel

10542.5.1 by Abel Deuring
let the checkwatches script log SQL statements
1
# Copyright 2010 Canonical Ltd.  This software is licensed under the
2
# GNU Affero General Public License version 3 (see the file LICENSE).
3
4
__metaclass__ = type
5
__all__ = [
6
    'LimitedList',
7
    ]
8
9
class LimitedList(list):
10542.5.4 by Abel Deuring
implemented reviewer's comments
10
    """A mutable sequence that takes a limited number of elements."""
10542.5.1 by Abel Deuring
let the checkwatches script log SQL statements
11
12
    def __new__(cls, max_length, value=None):
13
        return super(LimitedList, cls).__new__(cls)
14
15
    def __init__(self, max_length, value=None):
16
        if value is None:
17
            value = []
18
        elif len(value) > max_length:
19
            value = value[-max_length:]
20
        super(LimitedList, self).__init__(value)
21
        self.max_length = max_length
22
23
    def __repr__(self):
24
        return (
25
            '<LimitedList(%s, %s)>'
26
            % (self.max_length, super(LimitedList, self).__repr__()))
27
28
    def _ensureLength(self):
29
        """Ensure that the maximum length is not exceeded."""
30
        elements_to_drop = self.__len__() - self.max_length
31
        if elements_to_drop > 0:
32
            self.__delslice__(0, elements_to_drop)
33
34
    def __add__(self, other):
35
        return LimitedList(
36
            self.max_length, super(LimitedList, self).__add__(other))
37
38
    def __radd__(self, other):
39
        return LimitedList(self.max_length, other.__add__(self))
40
41
    def __iadd__(self, other):
42
        result = super(LimitedList, self).__iadd__(other)
43
        self._ensureLength()
44
        return result
45
46
    def __mul__(self, other):
47
        return LimitedList(
48
            self.max_length, super(LimitedList, self).__mul__(other))
49
50
    def __rmul__(self, other):
51
        return self.__mul__(other)
52
53
    def __imul__(self, other):
54
        result = super(LimitedList, self).__imul__(other)
55
        self._ensureLength()
56
        return result
57
58
    def __setslice__(self, i, j, sequence):
59
        result = super(LimitedList, self).__setslice__(i, j, sequence)
60
        self._ensureLength()
61
        return result
62
63
    def append(self, value):
64
        result = super(LimitedList, self).append(value)
65
        self._ensureLength()
66
        return result
67
68
    def extend(self, value):
69
        result = super(LimitedList, self).extend(value)
70
        self._ensureLength()
71
        return result
72
73
    def insert(self, position, value):
74
        result = super(LimitedList, self).insert(position, value)
75
        self._ensureLength()
76
        return result