I am extending the dict class in python:
JavaScript
x
18
18
1
import jmespath
2
import json
3
4
class superDict(dict):
5
def __init__(self, *args, **kwargs):
6
super().__init__(*args, **kwargs)
7
8
def prettyPrint(self):
9
print(self.pprettyPrint())
10
11
def pprettyPrint(self):
12
return json.dumps(self, indent=4, sort_keys=True, default=str)
13
14
def search(self, pattern):
15
return jmespath.search(pattern, self)
16
17
18
I would like to be able to do:
JavaScript
1
4
1
regDict = {"key": "value"}
2
super = superDict(regDict)
3
super.search('patern').prettyPrint()
4
the problem I have here is that jmespath can return a list, so I cannot do:
JavaScript
1
3
1
def search(self, pattern):
2
return superDict(jmespath.search(pattern, self))
3
Next idea would be creating a prettyprint class that superDict would inherit from and could also be used in the return of search:
JavaScript
1
10
10
1
class superDict(dict, prettyprint):
2
def __init__(self, *args, **kwargs):
3
super().__init__(*args, **kwargs)
4
5
6
def search(self, pattern):
7
return prettyprint(jmespath.search(pattern, self))
8
9
class prettyprint: ???
10
But I can’t figure out what the prettyprint class would look like for this to work. I basically can’t think of an elegant way to do this. Maybe some logic in init around the arg type would be simpler?
Advertisement
Answer
I ended up using new
JavaScript
1
39
39
1
class extensions:
2
def prettyPrint(self):
3
print(self.pprettyPrint())
4
return self
5
6
def pprettyPrint(self):
7
return json.dumps(self, indent=4, sort_keys=True, default=str)
8
9
def search(self, pattern):
10
return exJSON(jmespath.search(pattern, self))
11
12
class exList(list, extensions):
13
def prettyTable(self, headers):
14
x = PrettyTable()
15
x.field_names = headers
16
for row in self:
17
x.add_row(row.values())
18
x.align = "l"
19
print(x)
20
return self
21
22
class exDict(dict, extensions):
23
pass
24
25
class exStr(str, extensions):
26
pass
27
28
class exJSON:
29
def __new__(self, obj):
30
if type(obj) is dict:
31
return exDict(obj)
32
if type(obj) is list:
33
return exList(obj)
34
if type(obj) is str:
35
return exStr(obj)
36
else:
37
return obj
38
39