######################################################################## # ONLEY GROUP - www.onleygroup.com # # "Give Something Back Project" # # (useful code we give away) # # # # Copyright (c) 2012, Onley Group - givesomethingback@onleygroup.com # # # # Onley Free License (OFL): # # Permission to use, copy, modify, and/or distribute this software for # # any purpose with or without fee is hereby granted, provided that the # # above copyright notice and this permission notice appear in all # # copies and derivative works. # # # # You CAN sell this software. You CAN use this software in proprietary # # closed-source products. # # # # THE SOFTWARE IS PROVIDED "AS IS" AND ONLEY GROUP DISCLAIMS ALL # # WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED # # WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL ONLEY # # GROUP BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL # # DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA # # OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER # # TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR # # PERFORMANCE OF THIS SOFTWARE. # # ---------------------------------------------------------------------# # Title: TreePrint # # Language: Python # # Type: Function(s) # # Description: # # Displays nested lists / dicts / tuples in an aligned hierarchy to # # make debugging loops easy. Accepts all variable types, inc mixed. # # Usage: # # >>> treeprint(varname) # ######################################################################## def tree(var, level=1, outstr=''): #Takes a var, prints it out as nested aligned list if var is None: #Just return a new line: outstr+=' \n' elif isinstance(var, (int, float, long, complex, str, bool, unicode)): #Single value, simply add the fucker outstr+=' '+str(var) outstr+=' \n' elif isinstance(var, (list, tuple)): #List with some specified order, print in order outstr+='\n' k=0 #Manually index this for valchild in var: for tab in range(level-1): # Print key outstr+='\t' outstr+='['+str(k)+'] => ' k+=1 #Increment index newlevel = level + 1 outstr = tree(valchild,newlevel,outstr) elif isinstance(var,(dict)): #List with keys and values, no order outstr+='\n' for k,valchild in sorted(var.iteritems()): for tab in range(level-1): # Print key outstr+='\t' outstr+='['+str(k)+'] => ' newlevel = level + 1 outstr = tree(valchild,newlevel,outstr) else: #It doesn't qualify as any of the above cases outstr+=' '+str(var) outstr+=' \n' return outstr def treeprint(var): #Wrapper for tree outstr = tree(var) print outstr return outstr #Available to caller for wider use