summaryrefslogtreecommitdiffstats
path: root/mlplib/util.py
blob: 9bc1a1ffe0f207f1fe991e557b3cfeb2299a6bd1 (plain)
1
2
3
4
5
6
7
8
9
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
46
47
48
49
50
51
52
53
54
"""
# -*- coding: utf-8 -*-
#
# Copyright 2021 Michael Büsch <m@bues.ch>
#
# Licensed under the Apache License version 2.0
# or the MIT license, at your option.
# SPDX-License-Identifier: Apache-2.0 OR MIT
#
"""

__all__ = [
    "GenericIter",
    "pprint",
    "printlist",
]

from dataclasses import dataclass
from pprint import pprint
from typing import Any

def printlist(lst, prefix=""):
    if prefix:
        print(f"{prefix}:")
    for i, one in enumerate(lst):
        for j, line in enumerate(str(one).splitlines()):
            if j == 0:
                print(f"{i:02d}: {line}")
            else:
                print(f"    {line}")

@dataclass
class GenericIter(object):
    obj:    Any
    size:   int
    rev:    bool = False
    pos:    int = 0

    def __iter__(self):
        return self

    def _next(self):
        pos = self.pos
        if self.rev:
            if pos < 0:
                raise StopIteration
            self.pos -= 1
        else:
            if pos >= self.size:
                raise StopIteration
            self.pos += 1
        return self.obj, pos

# vim: ts=4 sw=4 expandtab
bues.ch cgit interface