Last active
January 20, 2016 12:00
-
-
Save amontalenti/507bdacede4e83fe64f2 to your computer and use it in GitHub Desktop.
Example of defining a custom data structure for arbitrarily-nestable trees.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Tree(dict): | |
| """A Tree is a dict-like object that nests arbitrarily. | |
| It supports both `tree["key"]` and `tree.key` syntax for lookups. | |
| A lookup for a missing key, by either syntax, results in creation | |
| of a new nested tree, e.g. | |
| >>> tree = Tree() | |
| >>> tree.a.b.c = "d" | |
| >>> tree | |
| Tree({'a': Tree({'b': Tree({'c': 'd'})})}) | |
| >>> tree["a"]["b"]["c"] | |
| 'd' | |
| """ | |
| def __getitem__(self, item): | |
| if not item.startswith("_") and item not in self: | |
| self[item] = Tree() | |
| return super(Tree, self).__getitem__(item) | |
| def __repr__(self): | |
| return "%s(%s)" % ( | |
| self.__class__.__name__, | |
| super(Tree, self).__repr__()) | |
| def __getattr__(self, item): | |
| if not item.startswith("_") and item not in self: | |
| self[item] = Tree() | |
| return self[item] | |
| def __setattr__(self, name, value): | |
| self[name] = value | |
| def __delattr__(self, name): | |
| del self[name] | |
| if __name__ == "__main__": | |
| import doctest | |
| doctest.testmod() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment