Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 0f15ba3

Browse files
committed
load_json_dict checks if file exists and returns {} if errors.
also, save_json_dict checks if what it's saving is a dictionary.
1 parent 223a0b7 commit 0f15ba3

File tree

1 file changed

+21
-16
lines changed

1 file changed

+21
-16
lines changed

plotly/utils.py

Lines changed: 21 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -12,25 +12,30 @@
1212

1313
### general file setup tools ###
1414

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):
1719
with open(filename, "r") as f:
1820
try:
1921
data = json.load(f)
22+
if not isinstance(data, dict):
23+
data = {}
2024
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))
2337
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.")
3439

3540

3641
### Custom JSON encoders ###
@@ -129,9 +134,9 @@ def decode_unicode(coll):
129134

130135

131136
### docstring templating ###
132-
def template_doc(**kwargs):
137+
def template_doc(**names):
133138
def _decorator(func):
134139
if func.__doc__ is not None:
135-
func.__doc__ = func.__doc__.format(**kwargs)
140+
func.__doc__ = func.__doc__.format(**names)
136141
return func
137142
return _decorator

0 commit comments

Comments
 (0)