Created
October 6, 2014 20:36
-
-
Save danvk/925f6cc25df1c9583157 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
class IgnoreSubtree(Exception): | |
pass | |
def preorder_traversal(obj): | |
try: | |
yield obj | |
except IgnoreSubtree: | |
return | |
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: | |
pass | |
from nose.tools import * | |
def test_ignore_subtree(): | |
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}: | |
iterator.throw(IgnoreSubtree) | |
eq_([obj, {'c': 3, 'd': 4}, 2], out) | |
# Expected vs. actual: | |
# [{'a': {'c': 3, 'd': 4}, 'b': 2}, {'c': 3, 'd': 4}, 2] | |
# [{'a': {'c': 3, 'd': 4}, 'b': 2}, {'c': 3, 'd': 4}, 4, 2] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See http://stackoverflow.com/a/26222805/388951