File: attrdict.py

package info (click to toggle)
python-awair 0.2.4-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,016 kB
  • sloc: python: 1,041; makefile: 12
file content (46 lines) | stat: -rw-r--r-- 1,418 bytes parent folder | download | duplicates (2)
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
"""Dict with attribute-like access."""

from typing import Any, Dict, KeysView

from python_awair import const


class AttrDict(Dict[str, Any]):
    """Dict with attribute-like access.

    For example, given an AttrDict *foo*, we could
    access its values via *foo["bar"]* or *foo.bar*.

    This is the parent class for the Sensors and Indices
    classes, and as such it renames some properties to
    friendlier names on initialization (but not anytime after).
    """

    def __init__(self, attrs: Dict[str, Any]) -> None:
        """Initialize, hiding known sensor aliases."""
        new_attrs = dict(attrs)
        for key, value in attrs.items():
            if key in const.SENSOR_TO_ALIAS:
                new_attrs[const.SENSOR_TO_ALIAS[key]] = value
                del new_attrs[key]

        super().__init__(new_attrs)

    def __getattr__(self, name: str) -> Any:
        """Return things in the dict via dot-notation."""
        if name in self:
            return self[name]

        raise AttributeError()

    def __setattr__(self, name: str, value: Any) -> None:
        """Set values in the dict via dot-notation."""
        self[name] = value

    def __delattr__(self, name: str) -> None:
        """Remove values from the dict via dot-notation."""
        del self[name]

    def __dir__(self) -> KeysView[str]:
        """Return dict keys as dir attributes."""
        return self.keys()