Skip to content

Instantly share code, notes, and snippets.

@danvk
Created October 6, 2014 20:52
Show Gist options
  • Save danvk/ec02c91d43c8f2edbb54 to your computer and use it in GitHub Desktop.
Save danvk/ec02c91d43c8f2edbb54 to your computer and use it in GitHub Desktop.
#!/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)
@danvk
Copy link
Author

danvk commented Oct 6, 2014

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