forked from Boris-code/feapder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathperfect_dict.py
More file actions
94 lines (81 loc) · 2.07 KB
/
perfect_dict.py
File metadata and controls
94 lines (81 loc) · 2.07 KB
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# -*- coding: utf-8 -*-
"""
Created on 2021/4/8 11:32 上午
---------
@summary:
---------
@author: Boris
@email: boris_liu@foxmail.com
"""
def ensure_value(value):
if isinstance(value, (list, tuple)):
_value = []
for v in value:
_value.append(ensure_value(v))
if isinstance(value, tuple):
value = tuple(_value)
else:
value = _value
if isinstance(value, dict):
return PerfectDict(value)
else:
return value
class PerfectDict(dict):
"""
>>> data = PerfectDict({"id":1, "url":"xxx"})
>>> data
{'id': 1, 'url': 'xxx'}
>>> data = PerfectDict(id=1, url="xxx")
>>> data
{'id': 1, 'url': 'xxx'}
>>> data.id
1
>>> data.get("id")
1
>>> data["id"]
1
>>> id, url = data
>>> id
1
>>> url
'xxx'
>>> data[0]
1
>>> data[1]
'xxx'
>>> data = PerfectDict({"a": 1, "b": {"b1": 2}, "c": [{"c1": [{"d": 1}]}]})
>>> data.b.b1
2
>>> data[1].b1
2
>>> data.get("b").b1
2
>>> data.c[0].c1
[{'d': 1}]
>>> data.c[0].c1[0]
{'d': 1}
"""
def __init__(self, _dict: dict = None, _values: list = None, **kwargs):
self.__dict__ = _dict or kwargs or {}
self.__dict__.pop("__values__", None)
super().__init__(self.__dict__, **kwargs)
self.__values__ = _values or list(self.__dict__.values())
def __getitem__(self, key):
if isinstance(key, int):
value = self.__values__[key]
else:
value = self.__dict__[key]
return ensure_value(value)
def __iter__(self, *args, **kwargs):
for value in self.__values__:
yield ensure_value(value)
def __getattribute__(self, item):
value = object.__getattribute__(self, item)
if item == "__dict__" or item == "__values__":
return value
return ensure_value(value)
def get(self, key, default=None):
if key in self.__dict__:
value = self.__dict__[key]
return ensure_value(value)
return default