def traverse_check_before(node, depth, cache): cache[node] = None print('__'*depth + node.name) for ref in node.refs: # we are about to recurse, first check if the node we want # to recurse on is in the cache if ref in cache: print('Already in cache: %s' % ref.name) continue # recurse if we reach this point traverse_cached(ref, depth+1, cache) def traverse_check_after(node, depth, cache): # we have just recursed, return if this node is already in # the cache if node in cache: print('Already in cache: %s' % node.name) return cache[node] = None print('__'*depth + node.name) for ref in node.refs: # recurse without exception traverse_cached(ref, depth+1, cache)