Skip to content

mutable_cycle

Provides a MutableCycle class.

MutableCycle

Bases: Generic[T]

Similar to itertools.cycle, with the addition of a .delete_item method, that removes an item from the cycle.

Source code in src/sesg/scopus/mutable_cycle.py
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
class MutableCycle(Generic[T]):
    """Similar to `itertools.cycle`, with the addition of a `.delete_item` method, that removes an item from the cycle."""  # noqa: E501

    def __init__(self, items: list[T]):
        """Creates a mutable cycle instance.

        Args:
            items (list[T]): Items to cycle through.
        """
        self.items = deque(items)

    def delete_item(self, item: T):
        """Deletes an item of the cycle, if it is present.

        Args:
            item (T): The item to remove.
        """
        if item in self.items:
            self.items.remove(item)

    def __iter__(self):
        """Returns an iterator."""
        return self

    def __next__(self) -> T:
        """Returns the next item of the cycle."""
        if not self.items:
            raise StopIteration()

        item = self.items.popleft()
        self.items.append(item)
        return item

    def __len__(self):
        """Returns the number of items in the cycle."""
        return len(self.items)

__init__(items)

Creates a mutable cycle instance.

Parameters:

Name Type Description Default
items list[T]

Items to cycle through.

required
Source code in src/sesg/scopus/mutable_cycle.py
13
14
15
16
17
18
19
def __init__(self, items: list[T]):
    """Creates a mutable cycle instance.

    Args:
        items (list[T]): Items to cycle through.
    """
    self.items = deque(items)

__iter__()

Returns an iterator.

Source code in src/sesg/scopus/mutable_cycle.py
30
31
32
def __iter__(self):
    """Returns an iterator."""
    return self

__len__()

Returns the number of items in the cycle.

Source code in src/sesg/scopus/mutable_cycle.py
43
44
45
def __len__(self):
    """Returns the number of items in the cycle."""
    return len(self.items)

__next__()

Returns the next item of the cycle.

Source code in src/sesg/scopus/mutable_cycle.py
34
35
36
37
38
39
40
41
def __next__(self) -> T:
    """Returns the next item of the cycle."""
    if not self.items:
        raise StopIteration()

    item = self.items.popleft()
    self.items.append(item)
    return item

delete_item(item)

Deletes an item of the cycle, if it is present.

Parameters:

Name Type Description Default
item T

The item to remove.

required
Source code in src/sesg/scopus/mutable_cycle.py
21
22
23
24
25
26
27
28
def delete_item(self, item: T):
    """Deletes an item of the cycle, if it is present.

    Args:
        item (T): The item to remove.
    """
    if item in self.items:
        self.items.remove(item)