File: accessors.py

package info (click to toggle)
python-pathable 0.4.4-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 188 kB
  • sloc: python: 968; makefile: 3
file content (58 lines) | stat: -rw-r--r-- 1,524 bytes parent folder | download
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
55
56
57
58
"""Pathable accessors module"""
from contextlib import contextmanager
from typing import Any
from typing import Dict
from typing import Hashable
from typing import Iterator
from typing import List
from typing import Mapping
from typing import Union


class BaseAccessor:
    """Base accessor."""

    def stat(self, parts: List[Hashable]) -> Dict[str, Any]:
        raise NotImplementedError

    def keys(self, parts: List[Hashable]) -> Any:
        raise NotImplementedError

    def len(self, parts: List[Hashable]) -> int:
        raise NotImplementedError

    @contextmanager
    def open(
        self, parts: List[Hashable]
    ) -> Iterator[Union[Mapping[Hashable, Any], Any]]:
        raise NotImplementedError


class LookupAccessor(BaseAccessor):
    """Accessor for object that supports __getitem__ lookups"""

    def __init__(self, lookup: Mapping[Hashable, Any]):
        self.lookup = lookup

    def stat(self, parts: List[Hashable]) -> Dict[str, Any]:
        raise NotImplementedError

    def keys(self, parts: List[Hashable]) -> Any:
        with self.open(parts) as d:
            return d.keys()

    def len(self, parts: List[Hashable]) -> int:
        with self.open(parts) as d:
            return len(d)

    @contextmanager
    def open(
        self, parts: List[Hashable]
    ) -> Iterator[Union[Mapping[Hashable, Any], Any]]:
        content = self.lookup
        for part in parts:
            content = content[part]
        try:
            yield content
        finally:
            pass