|
12 | 12 |
|
13 | 13 | ### general file setup tools ###
|
14 | 14 |
|
15 |
| -def load_json(filename, *args): |
16 |
| - if os.path.getsize(filename) > 0: |
| 15 | +def load_json_dict(filename, *args): |
| 16 | + """Checks if file exists. Returns {} if something fails.""" |
| 17 | + data = {} |
| 18 | + if os.path.exists(filename): |
17 | 19 | with open(filename, "r") as f:
|
18 | 20 | try:
|
19 | 21 | data = json.load(f)
|
| 22 | + if not isinstance(data, dict): |
| 23 | + data = {} |
20 | 24 | except:
|
21 |
| - # TODO: issue a warning and bubble it up |
22 |
| - data = "" |
| 25 | + pass # TODO: issue a warning and bubble it up |
| 26 | + if args: |
| 27 | + return {key: data[key] for key in args if key in data} |
| 28 | + return data |
| 29 | + |
| 30 | + |
| 31 | +def save_json_dict(filename, json_dict): |
| 32 | + """Will error if filename is not appropriate, but it's checked elsewhere. |
| 33 | + """ |
| 34 | + if isinstance(json_dict, dict): |
| 35 | + with open(filename, "w") as f: |
| 36 | + f.write(json.dumps(json_dict, indent=4)) |
23 | 37 | else:
|
24 |
| - data = "" |
25 |
| - if len(args) and data: |
26 |
| - return {key: data[key] for key in args} |
27 |
| - else: |
28 |
| - return data |
29 |
| - |
30 |
| - |
31 |
| -def save_json(filename, json_obj): |
32 |
| - with open(filename, "w") as f: |
33 |
| - f.write(json.dumps(json_obj, indent=4)) |
| 38 | + raise TypeError("json_dict was not a dictionay. couldn't save.") |
34 | 39 |
|
35 | 40 |
|
36 | 41 | ### Custom JSON encoders ###
|
@@ -129,9 +134,9 @@ def decode_unicode(coll):
|
129 | 134 |
|
130 | 135 |
|
131 | 136 | ### docstring templating ###
|
132 |
| -def template_doc(**kwargs): |
| 137 | +def template_doc(**names): |
133 | 138 | def _decorator(func):
|
134 | 139 | if func.__doc__ is not None:
|
135 |
| - func.__doc__ = func.__doc__.format(**kwargs) |
| 140 | + func.__doc__ = func.__doc__.format(**names) |
136 | 141 | return func
|
137 | 142 | return _decorator
|
0 commit comments