~divmod-dev/divmod.org/trunk

« back to all changes in this revision

Viewing changes to Epsilon/epsilon/view.py

  • Committer: Jean-Paul Calderone
  • Date: 2014-06-29 20:33:04 UTC
  • mfrom: (2749.1.1 remove-epsilon-1325289)
  • Revision ID: exarkun@twistedmatrix.com-20140629203304-gdkmbwl1suei4m97
mergeĀ lp:~exarkun/divmod.org/remove-epsilon-1325289

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# -*- test-case-name: epsilon.test.test_view -*-
2
 
 
3
 
"""
4
 
Utility functionality for creating wrapping sequences so as to transform
5
 
their indices in some manner.
6
 
"""
7
 
 
8
 
class SlicedView(object):
9
 
    """
10
 
    Wrapper around a sequence which allows indexing and non-extended
11
 
    slicing, adjusting all indices using a transformation defined by a
12
 
    L{slice} object.
13
 
 
14
 
    For example::
15
 
 
16
 
        s = ['a', 'b']
17
 
        t = SlicedView(s, slice(1, None))
18
 
        t[0] == 'b'
19
 
 
20
 
    @ivar sequence: The underlying sequence from which to retrieve elements.
21
 
    @ivar bounds: A C{slice} instance defining the boundaries of this view.
22
 
    """
23
 
 
24
 
    def __init__(self, sequence, bounds):
25
 
        self.sequence = sequence
26
 
        self.bounds = bounds
27
 
 
28
 
 
29
 
    def _getIndices(self):
30
 
        start, stop, step = self.bounds.indices(len(self.sequence))
31
 
        indices = xrange(start, stop, step)
32
 
        return indices
33
 
 
34
 
 
35
 
    def __getitem__(self, index):
36
 
        """
37
 
        Compute the index in the underlying sequence of the given view index
38
 
        and return the corresponding element.
39
 
 
40
 
        @raise IndexError: If C{index} is out of bounds for the view.
41
 
        @raise ValueError: If C{self.bounds} is out of bounds for
42
 
        C{self.sequence}.
43
 
        """
44
 
        if isinstance(index, slice):
45
 
            return SlicedView(self, index)
46
 
        return self.sequence[self._getIndices()[index]]
47
 
 
48
 
 
49
 
    def __len__(self):
50
 
        """
51
 
        Compute the length of this view onto the sequence and return it.
52
 
        """
53
 
        return len(self._getIndices())