Listing functions in a file IN ORDER

Ian Sparks Ian.Sparks at etrials.com
Tue Jun 29 15:28:18 EDT 2004


> Peter Otten wrote :
>
> import compiler
> 
> class Visitor:
>     def __init__(self, module, *args):
>         self.module = module
>         self.args = args
>     def visitFunction(self, node):
>         getattr(self.module, node.name)(*self.args)
> 
> def callInOrder(module, *args):
>     ast = compiler.parseFile(module.__file__)
>     compiler.walk(ast, Visitor(module, *args))
> 
> if __name__ == "__main__":
>     import xyz
>     callInOrder(xyz)
> </runxyz.py>
> 
> Not particularly elegant, but crazy enough to be worth posting...

Neat. I'll try it, thanks!

> -----Original Message-----
> From: Peter Otten [mailto:__peter__ at web.de]
> Sent: Tuesday, June 29, 2004 11:53 AM
> To: python-list at python.org
> Subject: Re: Listing functions in a file IN ORDER
> 
> 
> Ian Sparks wrote:
> 
> > I have a python file with a number of functions named with 
> the form doX so
> > :
> > 
> > doTask1
> > doThing
> > doOther
> > 
> > The order these are executed in is important and I want them to be
> > executed top-down. They all have the same parameter 
> signature so I'd like
> > to do :
> > 
> >     for name, func in vars(mymodule).items():
> >         if not name.startswith("do") and callable(func):
> >             apply(func,my_params)
> > 
> > but the problem is that the return from vars is not ordered 
> the same as in
> > the file. i.e. it could be
> > 
> > doOther
> > doTask1
> > doThing
> > 
> > The low tech solution is to use dir() and re-name the 
> functions to sort
> > alphabetically but perhaps there is a more elegant solution?
> 
> The following minimal code will break with methods and nested 
> functions.
> 
> <xyz.py>
> def z(): print  "ZZZ"
> def y(): print  "YYY"
> def x(): print  "XXX"
> </xyz.py>
> 
> <runxyz.py>
> import compiler
> 
> class Visitor:
>     def __init__(self, module, *args):
>         self.module = module
>         self.args = args
>     def visitFunction(self, node):
>         getattr(self.module, node.name)(*self.args)
> 
> def callInOrder(module, *args):
>     ast = compiler.parseFile(module.__file__)
>     compiler.walk(ast, Visitor(module, *args))
> 
> if __name__ == "__main__":
>     import xyz
>     callInOrder(xyz)
> </runxyz.py>
> 
> Not particularly elegant, but crazy enough to be worth posting...
> 
> Peter
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list
> 




More information about the Python-list mailing list