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