diff --git a/CHANGES.rst b/CHANGES.rst index a219bd1..bf9c2f9 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -11,5 +11,7 @@ To be released. - Added :mod:`nirum.datastructures` module and :class:`~nirum.datastructures.Map` which is an immutable dictionary. [:issue:`66`] +- Added :class:`nirum.datastructures.List` which is an immutable list. + [:issue:`49`] __ https://github.com/spoqa/nirum/blob/f1629787f45fef17eeab8b4f030c34580e0446b8/docs/serialization.md diff --git a/nirum/datastructures.py b/nirum/datastructures.py index 1b8c8e6..47682b3 100644 --- a/nirum/datastructures.py +++ b/nirum/datastructures.py @@ -6,7 +6,7 @@ """ import collections -__all__ = 'Map', +__all__ = 'List', 'Map' class Map(collections.Mapping): @@ -49,3 +49,27 @@ def __repr__(self): else: args = '' return '{0.__module__}.{0.__name__}({1})'.format(type(self), args) + + +class List(collections.Sequence): + + def __init__(self, l): + self.l = l + + def __getitem__(self, index): + return self.l[index] + + def __len__(self): + return len(self.l) + + def __contains__(self, item): + return item in self.l + + def __iter__(self): + return iter(self.l) + + def index(self, item): + return self.l.index(item) + + def count(self, item): + return self.l.count(item) diff --git a/nirum/deserialize.py b/nirum/deserialize.py index fe2173d..607f579 100644 --- a/nirum/deserialize.py +++ b/nirum/deserialize.py @@ -13,8 +13,8 @@ from iso8601 import iso8601, parse_date from six import text_type -from ._compat import get_tuple_param_types, get_union_types, is_union_type from .datastructures import Map +from ._compat import get_tuple_param_types, get_union_types, is_union_type __all__ = ( 'deserialize_abstract_type', diff --git a/tests/datastructures_test.py b/tests/datastructures_test.py index 1b82e5f..e59ef88 100644 --- a/tests/datastructures_test.py +++ b/tests/datastructures_test.py @@ -3,7 +3,7 @@ from pytest import raises -from nirum.datastructures import Map +from nirum.datastructures import List, Map def test_map_init(): @@ -68,3 +68,23 @@ def test_map_repr(): assert repr(Map()) == 'nirum.datastructures.Map()' assert repr(Map(a=1)) == "nirum.datastructures.Map({'a': 1})" assert repr(Map(a=1, b=2)) == "nirum.datastructures.Map({'a': 1, 'b': 2})" + + +def test_list(): + immutable_list = List([1, 2]) + with raises(AttributeError): + immutable_list.append(1) + + with raises(TypeError): + immutable_list + [3] + + assert isinstance(immutable_list, collections.Sequence) + assert not isinstance(immutable_list, collections.MutableSequence) + assert immutable_list[0] == 1 + assert len(immutable_list) == 2 + assert 2 in immutable_list + assert next(iter(immutable_list)) == 1 + assert immutable_list.index(2) == 1 + assert immutable_list.count(1) == 1 + assert immutable_list.count(2) == 1 + assert immutable_list.count(3) == 0