-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdotdict.py
executable file
·70 lines (57 loc) · 2.23 KB
/
dotdict.py
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 17 December 2012 by Eiríkur Hallgrímsson
# Character geek: The 2nd and 3rd i in my name have diacriticals.
# If there is a file-encoding cookie, Python will accept this. (2.x, too)
# 18 December 2012 EH Added StrictDotDict which doesn't allow new keys.
# 28 March 2013 EH PEP-8 compliance, requested by RackSpace
# 30 October 2015 Unused argument (Pylint) fix from John Anderson, janderson@soltra
# 27 September 2019 DotStore class adds simple persistance via JSON files.
"""Simple Library to hold the DotDict class."""
import os
import json
class DotDict(dict):
"""
Enable use of Javascript/Coffeescript style object notation for dicts.
The __missing__ method allows chaining creation of nested DotDicts:
a = DotDict() ; a.foo.bar = 'content'
Limitation: Expressing keys as attributes limits keys to valid Python
identifiers.
"""
__getattr__ = dict.__getitem__
__delattr__ = dict.__delitem__
def __setattr__(self, key, value):
if hasattr(value, 'keys'):
value = DotDict(value)
self[key] = value
def __missing__(self, key):
self[key] = DotDict()
return self[key]
class StrictDotDict(DotDict):
"""Strict form (subclass) of DotDict. Does not allow new keys."""
def __setattr__(self, key, value):
if key in self:
if hasattr(value, 'keys'):
value = DotDict(value)
self[key] = value
else:
raise KeyError
def __missing__(self, *args, **kwargs):
raise KeyError
class DotStore(DotDict):
"""
This is a simple backing store for DotDict.
"""
__getattr__ = dict.__getitem__
__delattr__ = dict.__delitem__
def __init__(self, filepath):
"Establish backing store."
if os.access(filepath, os.R_OK): # We can read it
self.update(json.load(open(filepath)))
else:
open(filepath, 'w').close() # If not writable, just allow exception.
self.store = filepath
def __setattr__(self, key, value):
"When modified, write to the backing file."
super().__setattr__(key, value) # Dict behavior handled in superclass
json.dump(self, open(self.store, 'w'), indent=4)