Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Interesting, I thought I was a rare breed using the following function quite a bit in my code. However, it seems these things are a dime a dozen. -- I modeled this one after the way Django does it. I think the only thing it does that yours doesn't is all a function if one of the dict values is an object. Thats useful for get_somevalue() type things on a tree of objects.

    def rget(obj, attrstr, default=None, delim='.'):
        try:
            parts = attrstr.split(delim, 1)
            attr = parts[0]
            attrstr = parts[1] if len(parts) == 2 else None
            if isinstance(obj, dict): value = obj[attr]
            elif isinstance(obj, list): value = obj[int(attr)]
            elif isinstance(obj, tuple): value = obj[int(attr)]
            elif isinstance(obj, object): value = getattr(obj, attr)
            if attrstr: return rget(value, attrstr, default, delim)
            return value
        except:
            return default


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: