I need to read values from a JSON input in python which might be missing any key or value in the input. I Wrote this wrapper around the builtin dicts of Python to make handling errors easier when the JSON input is missing keys or values.
class DictAccessor:
def __init__(self, to_access: Optional[Dict[Any, Any]]):
self._payload = to_access
def access(self, key: Any) -> "DictAccessor":
if isinstance(self._payload, dict):
return DictAccessor(self._payload.get(key))
return DictAccessor(None)
def get_value(self) -> Any:
return self._payload
def handle_error(self, err_callable: Callable[[None], None]) -> "DictAccessor":
if self._payload is None:
err_callable()
return self
def type_check(self, the_type) -> "DictAccessor":
if not isinstance(self._payload, the_type):
return DictAccessor(None)
return self
d = json.loads('{"a":{"c":42},"x":"x"}')
should_be_the_answer = DictAccessor(d)\
.access("a")\
.access("c")\
.type_check(int)\
.handle_error(lambda : print("err"))\
.get_value()
I know this is some design pattern I saw somewhere else (something related to functional programming i think). However, I can't recall the name. This code not just chaining (of function calls). There is also kinda the idea of a maybe in there but it also doesn't fully describe the pattern.
There also might be a variantion where get_value looks like this
def get_value(self, value_callback: Callable[[Any], None]) -> "DictAccessor":
value_callback(self._payload)
return self
How does one call this pattern of handling errors in a chain of operation or accesses where each one might fail?
Aucun commentaire:
Enregistrer un commentaire