MCPcopy Index your code
hub / github.com/bslatkin/effectivepython / divide_json

Function divide_json

example_code/item_080.py:130–157  ·  view source on GitHub ↗
(path)

Source from the content-addressed store, hash-verified

128DIE_IN_ELSE_BLOCK = False
129
130def divide_json(path):
131 print("* Opening file")
132 handle = open(path, "r+") # May raise OSError
133 try:
134 print("* Reading data")
135 data = handle.read() # May raise UnicodeDecodeError
136 print("* Loading JSON data")
137 op = json.loads(data) # May raise ValueError
138 print("* Performing calculation")
139 value = op["numerator"] / op["denominator"] # May raise ZeroDivisionError
140 except ZeroDivisionError:
141 print("* Handling ZeroDivisionError")
142 return UNDEFINED
143 else:
144 print("* Writing calculation")
145 op["result"] = value
146 result = json.dumps(op)
147 handle.seek(0) # May raise OSError
148 if DIE_IN_ELSE_BLOCK:
149 import errno
150 import os
151
152 raise OSError(errno.ENOSPC, os.strerror(errno.ENOSPC))
153 handle.write(result) # May raise OSError
154 return value
155 finally:
156 print("* Calling close()")
157 handle.close() # Always runs
158
159
160print("Example 9")

Callers 1

item_080.pyFile · 0.85

Calls 3

openFunction · 0.85
writeMethod · 0.80
readMethod · 0.45

Tested by

no test coverage detected