Recursive method

Hans Nowak ivnowa at hvision.nl
Tue Jul 13 17:18:40 EDT 1999


Ralph Gauges wrote:
> 
> Hello,
> 
> I am trying to generate a JTree (in JPython) out of some
> Data I have. The data I have is structured in classes which
> have a list of classes that have a list of classes and so
> on. Now I want to call the makenodes method with the top
> level class and have the function follow the tree
> recursively (see code below). Unfortunately all I get is a
> 'NameError' for makenodes, when the function is supposed to
> call itself. This seems to be a problem with the namespace,
> but I have no idea, how to solve this. Any help would be
> appreciated.
> Thanks a lot in advance
> 
> Ralph
> 
>         def makeTree():
>                 .
>                 .
>                 .
>             def makenodes(C):
> 
> N=javax.swing.tree.DefaultMutableTreeNode(C.Name)
>                 Children=C.getChildren()
>                 for Child in Children:
>                     N.add(makenodes(Child))
>                 return N
> 
>             for Class in M.Classes:
>                 ClassNode.add(makenodes(Class))
>                  .
>                  .
>                  .

You have a nested function here. (I say function, because it does not
look like a method... it's missing the self
argument! But maybe you didn't post the real code.) 

Anyway, makenodes is nested within makeTree, and that's the reason it
won't find itself... scope in Python is not
like C's or Pascal's. If makenodes were 'visible' from somewhere (e.g.
it would be global, accessible in a module, 
or directly in the class definition, then it would be no problem.
Recursive functions are usually no problem,
except in this case. *frown*  (This might be a FAQ... i'm too lazy to
look it up though. :)

So, to solve this, you could try a different approach... maybe

(you said it's a method, right?)

class Blahblah:
    ...
    def makeTree(self):
         ....
    def makenodes(self, C):
         ....

I don't know if this is possible in your case, but it could be a
solution.

Good luck,




More information about the Python-list mailing list