Hacker News new | ask | show | jobs
by emidln 4451 days ago
I'm perfectly fine with defining get and get_in ala Clojure and using them (they work on __getitem__ supporting things, so dicts, lists, strings, most random user-level containers). I go a bit further in my codebases and implement:

    def get(obj, k, default=None):
        """ safe __getitem__ obj[k] with a default """ 
    def assoc(obj, k, v):
        """ obj[k] = v returning obj """
    def dissoc(obj, k):
        """ safe del obj[k] returning obj without k""" 
    def get_in(obj, keys, default=None):
        """ __getitem__ obj[k0][k1][kn] with a default. """
    def assoc_in(obj, keys, v, default=lambda n: dict()):
        """ __setitem__ obj[k0][k1][kn] = v. __getitem__ failures handled with default """
    def dissoc_in(obj, keys):
        """ Return obj asserting that obj[k0][k1][kn] does not exist. """
    def update_in(obj, keys, update_fn=None, default=lambda n:dict()):
        """ Update the value at obj[k0][k1][kn] with update_fn returning obj. __getitem__ failures handled by default. """ 
    def merge_with(fn, **dictionaries):
        """ Merge resolving node conflicts with fn """
    def deep_merge_with(fn, **dictionaries):
        """ Recursively merge resolving node conflicts with fn"""
as a matter of course in most of python webapp and data munging projects. They are insanely useful when working with the gobs of JSON that is common when interacting with modern web services. I really should throw the implementations into a public library at this point.