Created
October 6, 2014 20:52
-
-
Save danvk/ec02c91d43c8f2edbb54 to your computer and use it in GitHub Desktop.
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
#!/usr/bin/env python | |
class IgnoreSubtree(Exception): | |
pass | |
def preorder_traversal(obj): | |
try: | |
yield obj | |
except IgnoreSubtree: | |
return | |
else: | |
if isinstance(obj, dict): | |
for k, v in obj.iteritems(): | |
iterator = preorder_traversal(v) | |
for o in iterator: | |
try: | |
yield o | |
except IgnoreSubtree as e: | |
try: | |
iterator.throw(e) | |
except StopIteration: | |
pass | |
from nose.tools import * | |
def test_ignore_subtree(): | |
obj = {'a': {'c': 3}, 'b': 2} | |
eq_([obj, {'c': 3}, 3, 2], list(preorder_traversal(obj))) | |
iterator = preorder_traversal(obj) | |
out = [] | |
for o in iterator: | |
out.append(o) | |
if o == {'c': 3}: | |
try: | |
val = iterator.throw(IgnoreSubtree) | |
except StopIteration: | |
pass | |
else: | |
out.append(val) | |
eq_([obj, {'c': 3}, 2], out) | |
def test_ignore_subtree2(): | |
obj = {'a': {'c': 3, 'd': 4}, 'b': 2} | |
eq_([obj, {'c': 3, 'd': 4}, 3, 4, 2], | |
list(preorder_traversal(obj))) | |
iterator = preorder_traversal(obj) | |
out = [] | |
for o in iterator: | |
out.append(o) | |
if o == {'c': 3, 'd': 4}: | |
try: | |
val = iterator.throw(IgnoreSubtree) | |
except StopIteration: | |
pass | |
else: | |
out.append(val) | |
eq_([obj, {'c': 3, 'd': 4}, 2], out) |
There's a bug in this code. If there are two adjacent {c: 3}
nodes (or whichever ones you want to filter out) in the object, then line 40 needs to throw()
another IgnoreSubtree
to the iterator. There's code that needs to be duplicated here.
My conclusion from all this is that subtree pruning should be done by passing in a callback, rather than throwing exceptions into the iterator.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See http://stackoverflow.com/questions/26221309/preorder-traversal-using-python-generators-with-a-mechanism-to-ignore-subtrees