The following code recursively processes a list of dictionaries into a tree while building an HTML output string. I'm getting a scope access error when trying to access the output string variable from within the recursing function. However, it has no problem accessing the nodes list object in the same scope- and in fact the function worked fine before I added the output var. What's the deal here?
Sample: http://ideone.com/Kg8ti
nodes = [
{ 'id':1, 'parent_id':None, 'name':'a' },
{ 'id':2, 'parent_id':None, 'name':'b' },
{ 'id':3, 'parent_id':2, 'name':'c' },
{ 'id':4, 'parent_id':2, 'name':'d' },
{ 'id':5, 'parent_id':4, 'name':'e' },
{ 'id':6, 'parent_id':None, 'name':'f' }
]
output = ''
def build_node(node):
output += '<li><a>'+node['name']+'</a>'
subnodes = [subnode for subnode in nodes if subnode['parent_id'] == node['id']]
if len(subnodes) > 0 :
output += '<ul>'
[build_node(subnode) for subnode in subnodes]
output += '</ul>'
output += '</li>'
return node
output += '<ul>'
node_tree = [build_node(node) for node in nodes if node['parent_id'] == None]
output += '</ul>'
import pprint
pprint.pprint(node_tree)
Error:
Traceback (most recent call last):
File "prog.py", line 23, in <module>
node_tree = [build_node(node) for node in nodes if node['parent_id'] == None]
File "prog.py", line 13, in build_node
output += '<li><a>'+node['name']+'</a>'
UnboundLocalError: local variable 'output' referenced before assignment