magicattr 0.1.7__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: magicattr
|
|
3
|
+
Version: 0.1.7
|
|
4
|
+
Summary: A getattr and setattr that works on nested objects, lists, dicts, and any combination thereof without resorting to eval
|
|
5
|
+
Home-page: https://github.com/frmdstryr/magicattr
|
|
6
|
+
Author: frmdstryr
|
|
7
|
+
Author-email: frmdstryr@gmail.com
|
|
8
|
+
License: MIT
|
|
9
|
+
Description-Content-Type: text/markdown
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Dynamic: author
|
|
12
|
+
Dynamic: author-email
|
|
13
|
+
Dynamic: description
|
|
14
|
+
Dynamic: description-content-type
|
|
15
|
+
Dynamic: home-page
|
|
16
|
+
Dynamic: license
|
|
17
|
+
Dynamic: license-file
|
|
18
|
+
Dynamic: summary
|
|
19
|
+
|
|
20
|
+
# Magicattr
|
|
21
|
+
|
|
22
|
+
[](https://github.com/frmdstryr/magicattr/actions)
|
|
23
|
+
[](https://codecov.io/gh/frmdstryr/magicattr)
|
|
24
|
+
[](https://pepy.tech/project/magicattr)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
A getattr and setattr that works on nested objects, lists,
|
|
28
|
+
dictionaries, and any combination thereof without resorting to eval.
|
|
29
|
+
|
|
30
|
+
It differs from getattr and setattr in that it retains the failure cause
|
|
31
|
+
instead of always raising an AttributeError.
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
### Example
|
|
36
|
+
|
|
37
|
+
Say we have a person class as follows:
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class Person:
|
|
43
|
+
settings = {
|
|
44
|
+
'autosave': True,
|
|
45
|
+
'style': {
|
|
46
|
+
'height': 30,
|
|
47
|
+
'width': 200
|
|
48
|
+
},
|
|
49
|
+
'themes': ['light', 'dark']
|
|
50
|
+
}
|
|
51
|
+
def __init__(self, name, age, friends):
|
|
52
|
+
self.name = name
|
|
53
|
+
self.age = age
|
|
54
|
+
self.friends = friends
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
bob = Person(name="Bob", age=31, friends=[])
|
|
58
|
+
jill = Person(name="Jill", age=29, friends=[bob])
|
|
59
|
+
jack = Person(name="Jack", age=28, friends=[bob, jill])
|
|
60
|
+
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
With magicattr we can do this
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
|
|
67
|
+
# Nothing new
|
|
68
|
+
assert magicattr.get(bob, 'age') == 31
|
|
69
|
+
|
|
70
|
+
# Lists
|
|
71
|
+
assert magicattr.get(jill, 'friends[0].name') == 'Bob'
|
|
72
|
+
assert magicattr.get(jack, 'friends[-1].age') == 29
|
|
73
|
+
|
|
74
|
+
# Dict lookups
|
|
75
|
+
assert magicattr.get(jack, 'settings["style"]["width"]') == 200
|
|
76
|
+
|
|
77
|
+
# Combination of lookups
|
|
78
|
+
assert magicattr.get(jack, 'settings["themes"][-2]') == 'light'
|
|
79
|
+
assert magicattr.get(jack, 'friends[-1].settings["themes"][1]') == 'dark'
|
|
80
|
+
|
|
81
|
+
# Setattr
|
|
82
|
+
magicattr.set(bob, 'settings["style"]["width"]', 400)
|
|
83
|
+
assert magicattr.get(bob, 'settings["style"]["width"]') == 400
|
|
84
|
+
|
|
85
|
+
# Nested objects
|
|
86
|
+
magicattr.set(bob, 'friends', [jack, jill])
|
|
87
|
+
assert magicattr.get(jack, 'friends[0].friends[0]') == jack
|
|
88
|
+
|
|
89
|
+
magicattr.set(jill, 'friends[0].age', 32)
|
|
90
|
+
assert bob.age == 32
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
You can also delete like this too.
|
|
94
|
+
|
|
95
|
+
```python
|
|
96
|
+
|
|
97
|
+
# Deletion
|
|
98
|
+
magicattr.delete(jill, 'friends[0]')
|
|
99
|
+
assert len(jill.friends) == 0
|
|
100
|
+
|
|
101
|
+
magicattr.delete(jill, 'age')
|
|
102
|
+
assert not hasattr(jill, 'age')
|
|
103
|
+
|
|
104
|
+
magicattr.delete(bob, 'friends[0].age')
|
|
105
|
+
assert not hasattr(jack, 'age')
|
|
106
|
+
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
What if someone tries to mess with you?
|
|
110
|
+
|
|
111
|
+
```python
|
|
112
|
+
|
|
113
|
+
# Unsupported
|
|
114
|
+
with pytest.raises(NotImplementedError) as e:
|
|
115
|
+
magicattr.get(bob, 'friends[0+1]')
|
|
116
|
+
|
|
117
|
+
with pytest.raises(SyntaxError) as e:
|
|
118
|
+
magicattr.get(bob, 'friends[')
|
|
119
|
+
|
|
120
|
+
with pytest.raises(ValueError) as e:
|
|
121
|
+
magicattr.get(bob, 'friends = [1,1]')
|
|
122
|
+
|
|
123
|
+
# Nice try, function calls are not allowed
|
|
124
|
+
with pytest.raises(ValueError):
|
|
125
|
+
magicattr.get(bob, 'friends.pop(0)')
|
|
126
|
+
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
Did I miss anything? Let me know!
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
#### What it can't do?
|
|
134
|
+
|
|
135
|
+
Slicing, expressions, function calls, append/pop from lists, eval stuff, etc...
|
|
136
|
+
|
|
137
|
+
#### How does it work?
|
|
138
|
+
|
|
139
|
+
Parses the attr string into an ast node and manually evaluates it.
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
### Installing
|
|
143
|
+
|
|
144
|
+
`pip install magicattr`
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
### License
|
|
148
|
+
|
|
149
|
+
MIT
|
|
150
|
+
|
|
151
|
+
Hope it helps, cheers!
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
magicattr.py,sha256=vMavZii2kH6KEUH5BRGalUKx701SfKJ2VoT7IXBqpQg,5252
|
|
2
|
+
magicattr-0.1.7.dist-info/licenses/LICENSE,sha256=PXZ_zu4-PDlIRHf6gRADkw9r7uHWKi4L4Vlzy_4kJX4,1066
|
|
3
|
+
magicattr-0.1.7.dist-info/METADATA,sha256=3JpxVI4F2s0894ykI7nEUo5Lw0EYlHO-P-P_2KVwTW0,3464
|
|
4
|
+
magicattr-0.1.7.dist-info/WHEEL,sha256=YVMoNqKzERt-wjUZwJ33xBGAwnFl-4cqbYkTtWa4itE,91
|
|
5
|
+
magicattr-0.1.7.dist-info/top_level.txt,sha256=c5xmvEG39EMqzKSEPQ6Xp1tP6nu7zmt5TpKFzrAb_j0,10
|
|
6
|
+
magicattr-0.1.7.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2018 frmdstryr
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
magicattr
|
magicattr.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Copyright (c) 2018-2022, Jairus Martin.
|
|
3
|
+
|
|
4
|
+
Distributed under the terms of the MIT License.
|
|
5
|
+
|
|
6
|
+
The full license is in the file LICENSE, distributed with this software.
|
|
7
|
+
|
|
8
|
+
Created on June, 2018
|
|
9
|
+
"""
|
|
10
|
+
import ast
|
|
11
|
+
import sys
|
|
12
|
+
from functools import reduce
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
#: Types of AST nodes that are used
|
|
16
|
+
_AST_TYPES = (ast.Name, ast.Attribute, ast.Subscript, ast.Call)
|
|
17
|
+
_STRING_TYPE = basestring if sys.version_info.major == 2 else str
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def get(obj, attr, **kwargs):
|
|
21
|
+
"""A getattr that supports nested lookups on objects, dicts, lists, and
|
|
22
|
+
any combination in between.
|
|
23
|
+
|
|
24
|
+
Parameters
|
|
25
|
+
---------
|
|
26
|
+
obj: Object
|
|
27
|
+
An object to lookup the attribute on
|
|
28
|
+
attr: String
|
|
29
|
+
A attribute string to lookup
|
|
30
|
+
kwargs:
|
|
31
|
+
default: Any
|
|
32
|
+
A default value used as a fallback if attr doesn't exist
|
|
33
|
+
|
|
34
|
+
Returns
|
|
35
|
+
-------
|
|
36
|
+
result: Object
|
|
37
|
+
The object retrieved or the default fallback value, if it was passed
|
|
38
|
+
"""
|
|
39
|
+
for chunk in _parse(attr):
|
|
40
|
+
try:
|
|
41
|
+
obj = _lookup(obj, chunk)
|
|
42
|
+
except Exception as ex:
|
|
43
|
+
if "default" in kwargs:
|
|
44
|
+
return kwargs["default"]
|
|
45
|
+
else:
|
|
46
|
+
raise ex
|
|
47
|
+
return obj
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def set(obj, attr, val):
|
|
51
|
+
"""A setattr that supports nested lookups on objects, dicts, lists, and
|
|
52
|
+
any combination in between.
|
|
53
|
+
|
|
54
|
+
Parameters
|
|
55
|
+
---------
|
|
56
|
+
obj: Object
|
|
57
|
+
An object to lookup the attribute on
|
|
58
|
+
attr: String
|
|
59
|
+
A attribute string to lookup
|
|
60
|
+
val: Object
|
|
61
|
+
The value to set
|
|
62
|
+
|
|
63
|
+
"""
|
|
64
|
+
obj, attr_or_key, is_subscript = lookup(obj, attr)
|
|
65
|
+
if is_subscript:
|
|
66
|
+
obj[attr_or_key] = val
|
|
67
|
+
else:
|
|
68
|
+
setattr(obj, attr_or_key, val)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def delete(obj, attr):
|
|
72
|
+
"""A delattr that supports deletion of a nested lookups on objects,
|
|
73
|
+
dicts, lists, and any combination in between.
|
|
74
|
+
|
|
75
|
+
Parameters
|
|
76
|
+
---------
|
|
77
|
+
obj: Object
|
|
78
|
+
An object to lookup the attribute on
|
|
79
|
+
attr: String
|
|
80
|
+
A attribute string to lookup
|
|
81
|
+
"""
|
|
82
|
+
obj, attr_or_key, is_subscript = lookup(obj, attr)
|
|
83
|
+
if is_subscript:
|
|
84
|
+
del obj[attr_or_key]
|
|
85
|
+
else:
|
|
86
|
+
delattr(obj, attr_or_key)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def lookup(obj, attr):
|
|
90
|
+
"""Like get but instead of returning the final value it returns the
|
|
91
|
+
object and action that will be done. This is useful if you need to do
|
|
92
|
+
any final checking (such as type validation) before doing a final setattr
|
|
93
|
+
or delattr.
|
|
94
|
+
|
|
95
|
+
Parameters
|
|
96
|
+
----------
|
|
97
|
+
obj: Object
|
|
98
|
+
An object to lookup the attribute on
|
|
99
|
+
attr: String
|
|
100
|
+
A attribute string to lookup
|
|
101
|
+
|
|
102
|
+
Returns
|
|
103
|
+
-------
|
|
104
|
+
result: Tuple[Object, String, Bool]
|
|
105
|
+
_ A tuple of the object, the attribute, dict key, or list index that
|
|
106
|
+
will be used, and whether the former is a subscript operation.
|
|
107
|
+
"""
|
|
108
|
+
nodes = tuple(_parse(attr))
|
|
109
|
+
if len(nodes) > 1:
|
|
110
|
+
obj = reduce(_lookup, nodes[:-1], obj)
|
|
111
|
+
node = nodes[-1]
|
|
112
|
+
else:
|
|
113
|
+
node = nodes[0]
|
|
114
|
+
if isinstance(node, ast.Attribute):
|
|
115
|
+
return obj, node.attr, False
|
|
116
|
+
elif isinstance(node, ast.Subscript):
|
|
117
|
+
return obj, _lookup_subscript_value(node.slice), True
|
|
118
|
+
elif isinstance(node, ast.Name):
|
|
119
|
+
return obj, node.id, False
|
|
120
|
+
raise NotImplementedError("Node is not supported: %s" % node)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _parse(attr):
|
|
124
|
+
"""Parse and validate an attr string
|
|
125
|
+
|
|
126
|
+
Parameters
|
|
127
|
+
----------
|
|
128
|
+
attr: String
|
|
129
|
+
|
|
130
|
+
Returns
|
|
131
|
+
-------
|
|
132
|
+
nodes: List
|
|
133
|
+
List of ast nodes
|
|
134
|
+
|
|
135
|
+
"""
|
|
136
|
+
if not isinstance(attr, _STRING_TYPE):
|
|
137
|
+
raise TypeError("Attribute name must be a string")
|
|
138
|
+
nodes = ast.parse(attr).body
|
|
139
|
+
if not nodes or not isinstance(nodes[0], ast.Expr):
|
|
140
|
+
raise ValueError("Invalid expression: %s" % attr)
|
|
141
|
+
return reversed([n for n in ast.walk(nodes[0]) if isinstance(n, _AST_TYPES)])
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _lookup_subscript_value(node):
|
|
145
|
+
"""Lookup the value of ast node.
|
|
146
|
+
|
|
147
|
+
Parameters
|
|
148
|
+
---------
|
|
149
|
+
node: ast.Constant, ast.Index, ast.UnaryOp
|
|
150
|
+
Node to lookup the value of
|
|
151
|
+
|
|
152
|
+
Returns
|
|
153
|
+
-------
|
|
154
|
+
result: Object
|
|
155
|
+
The object retrieved
|
|
156
|
+
"""
|
|
157
|
+
if isinstance(node, ast.Index):
|
|
158
|
+
node = node.value # For backwards compatibility
|
|
159
|
+
# Handle indexes and string keys
|
|
160
|
+
if isinstance(node, ast.Constant):
|
|
161
|
+
return node.value
|
|
162
|
+
# Handle negative indexes
|
|
163
|
+
elif (
|
|
164
|
+
isinstance(node, ast.UnaryOp)
|
|
165
|
+
and isinstance(node.op, ast.USub)
|
|
166
|
+
and isinstance(node.operand, ast.Constant)
|
|
167
|
+
):
|
|
168
|
+
return -node.operand.value
|
|
169
|
+
raise NotImplementedError("Subscript node is not supported: " "%s" % ast.dump(node))
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
def _lookup(obj, node):
|
|
173
|
+
"""Lookup the given ast node on the object.
|
|
174
|
+
|
|
175
|
+
Parameters
|
|
176
|
+
---------
|
|
177
|
+
obj: Object
|
|
178
|
+
An object to lookup the attribute, index, or key
|
|
179
|
+
node: ast.Attribute, ast.Name, or ast.Subscript
|
|
180
|
+
Node to lookup
|
|
181
|
+
|
|
182
|
+
Returns
|
|
183
|
+
-------
|
|
184
|
+
result: Object
|
|
185
|
+
The object retrieved
|
|
186
|
+
"""
|
|
187
|
+
if isinstance(node, ast.Attribute):
|
|
188
|
+
return getattr(obj, node.attr)
|
|
189
|
+
elif isinstance(node, ast.Subscript):
|
|
190
|
+
return obj[_lookup_subscript_value(node.slice)]
|
|
191
|
+
elif isinstance(node, ast.Name):
|
|
192
|
+
return getattr(obj, node.id)
|
|
193
|
+
elif isinstance(node, ast.Call):
|
|
194
|
+
raise ValueError("Function calls are not allowed.")
|
|
195
|
+
raise NotImplementedError("Node is not supported: %s" % node)
|