File: collections.py

package info (click to toggle)
python-astropy 1.3-8~bpo8%2B2
  • links: PTS, VCS
  • area: main
  • in suites: jessie-backports
  • size: 44,292 kB
  • sloc: ansic: 160,360; python: 137,322; sh: 11,493; lex: 7,638; yacc: 4,956; xml: 1,796; makefile: 474; cpp: 364
file content (52 lines) | stat: -rw-r--r-- 1,388 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
A module containing specialized collection classes.
"""


class HomogeneousList(list):
    """
    A subclass of list that contains only elements of a given type or
    types.  If an item that is not of the specified type is added to
    the list, a `TypeError` is raised.
    """
    def __init__(self, types, values=[]):
        """
        Parameters
        ----------
        types : sequence of types
            The types to accept.

        values : sequence, optional
            An initial set of values.
        """
        self._types = types
        list.__init__(self, values)

    def _assert(self, x):
        if not isinstance(x, self._types):
            raise TypeError(
                "homogeneous list must contain only objects of "
                "type '{}'".format(self._types))

    def __iadd__(self, other):
        for x in other:
            self._assert(x)
        return list.__iadd__(self, other)

    def __setitem__(self, x):
        self._assert(x)
        return list.__setitem__(self, x)

    def append(self, x):
        self._assert(x)
        return list.append(self, x)

    def insert(self, i, x):
        self._assert(x)
        return list.insert(self, i, x)

    def extend(self, x):
        for item in x:
            self._assert(item)
        return list.extend(self, x)