Traversing through Dir()

Dave Angel davea at ieee.org
Sat Mar 27 06:18:40 EDT 2010



Andrej Mitrovic wrote:
> On Mar 26, 9:18 am, "Alf P. Steinbach" <al... at start.no> wrote:
>   
>> <snip>
>> hierarchy =nspect.getclasstree( classes )
>> # 'hierarchy' is a list array of tuples and nested list arrays of the same form.
>> # The top level is an array of two items, the first item a tuple describing the
>> 'object'
>> # class, and the second item a list array representing the BaseException hierarchy.
>> print_hierarchy( hierarchy[1], level = )
>> </code>
>>
>> Cheers & hth.,
>>
>> - Alf
>>     
>
> Thanks for all of that. And yes, I've noticed I get into infinite
> recursions all the time, which is why I was asking if there was a
> simple way to do this. I'll have a look at these later.
>
> Kind regards,
> Andrej Mitrovic
>
>   
I can't help with the original question, but generally the cure for 
getting into infinite recursion when traversing a tree with multiple 
connections is to keep a set() of all visited nodes.  Whenever you hit a 
node a second time, don't visit it or its dependents.  It's not hard to 
add to otherwise working code, and frequently the easiest place is right 
at the beginning of the recursive function.
       if new_node in myset:
             return
      myset.add(new_node)
     ...process_this_node...
     for child in new_node:
           ...recurse...

HTH
DaveA




More information about the Python-list mailing list