Skip to content

Commit

Permalink
Merge 3eb6f8b into 33b561b
Browse files Browse the repository at this point in the history
  • Loading branch information
wanaryytel committed Feb 27, 2018
2 parents 33b561b + 3eb6f8b commit 6e7f4cd
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 1 deletion.
11 changes: 11 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,17 @@ Added indicies are filled with None by default.
>>> l
[None, None, 'C', None, None]

However, you can specify initial values to the list just like in defaultdict.

>>> l = defaultlist(None, [123, 'abc', 'qwerty'])
>>> l
[123, 'abc', 'qwerty']
>>> l[8] = "C"
>>> l
[123, 'abc', 'qwerty', None, None, None, None, None, 'C']
>>> l[4]
>>>

Slices and negative indicies are supported likewise

>>> l[1:4]
Expand Down
14 changes: 13 additions & 1 deletion defaultlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,17 @@
>>> l
[None, None, 'C', None, None]
However, you can specify initial values to the list just like in defaultdict.
>>> l = defaultlist(None, [123, 'abc', 'qwerty'])
>>> l
[123, 'abc', 'qwerty']
>>> l[8] = "C"
>>> l
[123, 'abc', 'qwerty', None, None, None, None, None, 'C']
>>> l[4]
>>>
Slices and negative indicies are supported likewise
>>> l[1:4]
Expand Down Expand Up @@ -70,7 +81,7 @@

class defaultlist(list):

def __init__(self, factory=None):
def __init__(self, factory=None, *args, **kwargs):
"""
List extending automatically to the maximum requested length.
Expand All @@ -79,6 +90,7 @@ def __init__(self, factory=None):
factory: Function called for every missing index.
"""
self.__factory = factory or defaultlist.__nonefactory
list.__init__(self, *args, **kwargs)

@staticmethod
def __nonefactory():
Expand Down
16 changes: 16 additions & 0 deletions tests/test_defaultdict.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,3 +183,19 @@ def test_len():
eq_(len(l), 3)
l[4]
eq_(len(l), 5)

def test_initial_data():
l = defaultlist(None, ['a', 'b'])
eq_(len(l), 2)
l[15] = 42
eq_(len(l), 16)
eq_(l[1], 'b')

l2 = defaultlist(None, [None, None, 1, None])
eq_(len(l2), 4)
l2[1] = 'q'
eq_(l2[1:3], ['q', 1])
eq_(l2[-1], None)
l2[-1] = 'last?'
eq_(l2[-1], 'last?')

0 comments on commit 6e7f4cd

Please sign in to comment.