3

I'm building a recursively method that uses a list of strings and integers (the 'path') to return an item from a nested structure of generic classes, lists, tuples, dictionaries.

def get_leaf(pytree, path):
    """
    Recuses down the path of the pytree
    """
    key = path[0]
    pytree = pytree.__dict__[key] if hasattr(pytree, '__dict__') else pytree[key]
    
    # Return param if at the end of path, else recurse
    return pytree if len(path) == 1 else get_leaf(pytree, path[1:])

This method works fine for most data types, but it fails when using ordered dictionaries because they have an __dict__ method, but this method always returns an empty dictionary.

from collections import OrderedDict
ordered_dict = OrderedDict({"item": 1})
print(ordered_dict.__dict__)
>>> {}

I don't understand why the ordered dictionary has this method, or why it always returns an empty dictionary.

Adam.Er8
  • 12,675
  • 3
  • 26
  • 38
  • because this method is not inherited from builtedin.dict, and is custom defined – sahasrara62 Sep 11 '22 at 12:10
  • @sahasrara62 It has nothing to do with inheritance, the `__dict__` attribute (it is not a method) contains the object's own attributes, and dictionary members are not attributes so they aren't in there. – kaya3 Sep 11 '22 at 12:12
  • Regarding your actual problem, I think it would make more sense to use `__getitem__` if it exists, and fallback to `__dict__` otherwise. – kaya3 Sep 11 '22 at 12:16

0 Answers0