Skip to content

Commit

Permalink
Update test_LazySequence.py (#3)
Browse files Browse the repository at this point in the history
* Update test_LazySequence.py

add last item test

* bugfix

* add docstrings

* update version test
  • Loading branch information
PythonFZ authored Feb 6, 2023
1 parent 6273b61 commit 6d59091
Show file tree
Hide file tree
Showing 7 changed files with 221 additions and 144 deletions.
292 changes: 158 additions & 134 deletions poetry.lock

Large diffs are not rendered by default.

15 changes: 14 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "ZnSlice"
version = "0.1.1"
version = "0.1.2"
description = "Cache, advanced slicing and lazy loading for __getitem__"
license = "Apache-2.0"
authors = ["zincwarecode <[email protected]>"]
Expand Down Expand Up @@ -40,3 +40,16 @@ exclude_lines = [
"if __name__ == .__main__.:"
]
ignore_errors = true

[tool.ruff]
select = ["E", "F", "D", "N", "C"]
extend-ignore = [
"C901",
"D213", "D203",
"D401",
"N802", "N801"
]

exclude = [
"tests",
]
1 change: 1 addition & 0 deletions tests/test_LazySequence.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ def test_LazySequenceInit():
assert lst[0] == 1
assert lst[[0, 2]].tolist() == [1, 3]
assert len(lst) == 3
assert lst[-1] == 3


def test_LazySequence_empty_Init():
Expand Down
2 changes: 1 addition & 1 deletion tests/test_znslice.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

def test_version():
"""Test 'ZnTrack' version."""
assert znslice.__version__ == "0.1.1"
assert znslice.__version__ == "0.1.2"


class CacheList(collections.abc.Sequence):
Expand Down
4 changes: 3 additions & 1 deletion znslice/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
"""The znslice package."""
import importlib.metadata

from znslice import utils
from znslice.znslice import LazySequence, Reset, znslice

__all__ = ["znslice", "LazySequence", "Reset"]
__all__ = ["znslice", "LazySequence", "Reset", "utils"]
__version__ = importlib.metadata.version("znslice")
22 changes: 18 additions & 4 deletions znslice/utils.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,19 @@
"""ZnSlice utils module."""
import functools


def optional_kwargs_decorator(fn):
"""Decorator to allow optional kwargs."""

@functools.wraps(fn)
def wrapped_decorator(*args, **kwargs):
"""The wrapped decorator."""
if len(args) == 1 and callable(args[0]):
return fn(args[0])

@functools.wraps(fn)
def real_decorator(decoratee):
"""The real decorator."""
return fn(decoratee, *args, **kwargs)

return real_decorator
Expand All @@ -18,30 +23,39 @@ def real_decorator(decoratee):

@functools.singledispatch
def item_to_indices(item, self):
"""Convert item to indices."""
raise ValueError(f"Cannot handle item of type {type(item)}")


@item_to_indices.register
def _(item: int, self):
def _(item: int, self) -> int:
"""Keep int as is."""
return item


@item_to_indices.register
def _(item: list, self):
def _(item: list, self) -> list:
"""Keep list as is."""
return item


@item_to_indices.register
def _(item: tuple, self):
def _(item: tuple, self) -> list:
"""Convert tuple to list."""
return list(item)


@item_to_indices.register
def _(item: slice, self):
def _(item: slice, self) -> list:
"""Convert slice to list using the length of the item."""
return list(range(len(self)))[item]


def handle_item(indices, cache, func, self, advanced_slicing=False) -> list:
"""Handle item.
TODO ...
"""
if advanced_slicing:
if new_indices := [x for x in indices if x not in cache]:
# only if len(new_indices) > 0
Expand Down
29 changes: 26 additions & 3 deletions znslice/znslice.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
"""The main znslice module."""
import collections.abc
import functools
import logging
Expand All @@ -13,6 +14,7 @@ class Reset:
"""Reset the cache for the given items."""

def __init__(self, item):
"""Initialize the Reset object."""
self.item = item


Expand All @@ -25,6 +27,10 @@ def __init__(
indices: typing.List[typing.Union[list, int]],
lazy_single_item: bool = False,
):
"""Initialize the LazySequence.
Todo: ...
"""
self._obj = obj
self._indices = indices
self._lazy_single_item = lazy_single_item
Expand All @@ -40,10 +46,14 @@ def from_obj(cls, obj, /, indices: list = None, lazy_single_item=False):
Parameters
----------
cls: LazySequence
the LazySequence class.
obj: list
list to create a LazySequence from.
indices: list, optional
list of indices to gather from obj. If None, all items in obj are used.
lazy_single_item: bool, optional
currently unused.
Returns
-------
Expand All @@ -61,6 +71,14 @@ def _(cls, obj, /, indices: list = None, lazy_single_item=False):
return cls([obj], [indices], lazy_single_item=False)

def __getitem__(self, item):
"""Get item from LazySequence.
Todo ...
"""
if item == -1:
# special case, return last entry
return self[len(self) - 1]

indices = utils.item_to_indices(item, self)
single_item = False
if isinstance(indices, int):
Expand Down Expand Up @@ -90,13 +108,16 @@ def __getitem__(self, item):
else lazy_sequence
)

def __repr__(self):
def __repr__(self) -> str:
"""Return the representation of the LazySequence."""
return f"{type(self).__name__}({self._obj}, {self._indices})"

def __len__(self):
def __len__(self) -> int:
"""Return the length of the LazySequence."""
return sum(len(x) for x in self._indices)

def __add__(self, other):
"""Add two LazySequences."""
if isinstance(other, LazySequence):
return self._get_new_instance(
self._obj + other._obj,
Expand All @@ -109,7 +130,8 @@ def __add__(self, other):
else:
raise TypeError("Can only add LazySequence to {LazySequence, list}")

def tolist(self):
def tolist(self) -> list:
"""Return the LazySequence as a non-lazy list."""
data = []
for obj, indices in zip(self._obj, self._indices):
if isinstance(indices, int):
Expand Down Expand Up @@ -159,6 +181,7 @@ def wrapper(self, item, _resolve: bool = False):
Parameters
----------
self: object
the class instance.
item: int, slice, list, tuple, Reset
The item to get.
_resolve: bool, default=False
Expand Down

0 comments on commit 6d59091

Please sign in to comment.