python - How is the programming pattern called that I used here (to simplify error handling during dictionary accesses)? -


i need read values json input in python might missing key or value in input. wrote wrapper around builtin dicts of python make handling errors easier when json input 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 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 design pattern saw somewhere else (something related functional programming think). however, can't recall name. code not chaining (of function calls). there kinda idea of maybe in there doesn't describe pattern.

there might variantion get_value looks this

    def get_value(self, value_callback: callable[[any], none]) -> "dictaccessor":         value_callback(self._payload)         return self 

how 1 call pattern of handling errors in chain of operation or accesses each 1 might fail?


Comments

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

angular - DownloadURL return null in below code -

php - Cannot override Laravel Spark authentication with own implementation -