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.