Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Wanaryytel master #4

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,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
18 changes: 17 additions & 1 deletion defaultlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,16 @@
>>> l[-3]
'C'

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]

Simple factory functions can be created via `lambda`.

>>> l = defaultlist(lambda: 'empty')
Expand Down Expand Up @@ -73,8 +83,14 @@ class defaultlist(list):
factory: Function called for every missing index.
"""

def __init__(self, factory=None):
def __init__(self, factory=None, data=None):
self.__factory = factory or defaultlist.__nonefactory
if data:
list.__init__(self, data)
else:
list.__init__(
self,
)

@staticmethod
def __nonefactory():
Expand Down
17 changes: 17 additions & 0 deletions tests/test_defaultlist.py
Original file line number Diff line number Diff line change
Expand Up @@ -189,3 +189,20 @@ def test_len():
assert len(dfl) == 3
assert dfl[4] is None
assert len(dfl) == 5


def test_initial_data():
"""Initial Data"""
dfl = defaultlist(None, ["a", "b"])
assert len(dfl) == 2
dfl[15] = 42
assert len(dfl) == 16
assert dfl[1] == "b"

dfl2 = defaultlist(None, [None, None, 1, None])
assert len(dfl2) == 4
dfl2[1] = "q"
assert dfl2[1:3] == ["q", 1]
assert dfl2[-1] is None
dfl2[-1] = "last?"
assert dfl2[-1] == "last?"